Download as pdf or txt
Download as pdf or txt
You are on page 1of 51

Javascript in a nutshell

Corso di Laurea Magistrale in Scienze di Internet


Knowledge Management

Andrea Nuzzolese

http://creativecommons.org/licenses/by-sa/3.0
Outline

• Javascript

• AJAX

• JSON

• jQuery

2
History of JavaScript

• Originally developed by Brendan Eich at Netscape in 1995 under


the name Mocha later renamed LiveScript

• Renamed JavaScript when Netscape added support for Java


technology (developed by Sun)
✦ This is characterized by many as a marketing ploy and by others asthe
result of a co-marketing deal between Netscape and Sun

• Standardized by ECMA Internation in 1997 as ECMAScript

• Most used extension of ECMAScript are to date:


✦ JavaScript
✦ JSript (developed by Microsoft)

3
JavaScript and HTML

• JavaScript code can be embedded in HTML documents in three


ways
✦ <script> tag, which contains JavaScript code
<script type="text/javascript">
alert("Hello word");
</script>

✦ <script> tag, which refers to external source


<script src="helloWorld.js”>
</script>

✦ in HTML code for managing events


<input type=“button” onclick=“alert(‘Hello, world!’)”>
...
<a href=“javascript:helloWorld()”>Say hello!</a>

4
Base syntax

• JavaScript is case-sensitive
✦ helloWorld != helloworld

• Variables
✦ have no type declaration
✦ var y; is the declaration of a variable y

• Operators <script type="text/javascript">


var y = “now y is typed as a String”;
✦ “=” assignment y = 10; // now y is typed as int
y = 10.5; // now y is typed as float
</script>

✦ “+” sum in case of both arguments are numbers and concat in case of one
of them is a string <script type="text/javascript">
var y = “Steve ”;
var x = y + “Jobs” // x = “Steve Jobs”
y = 10;
x = y + 5; // x = 15
</script> 5
Conditional statments: if...else and while

<script type="text/javascript">
var y = 4;
var greaterThanZero;
// if...else statement
if(y > 0){
greaterThanZero = true;
}
else{
greaterThanZero = false;
}
// while statement
while(greaterThanZero){
y -= 1; // syntax sugar for y = y - 1;
if(y == 0){
greaterThanZero = !greaterThanZero;
}
}

</script>

6
Conditional statements: for and switch...case

<script type="text/javascript">
// for statement
for(var i=0; i<10; i++){
alert(“The value of i is: ” + i);
}
else{
greaterThanZero = false;
}
// switch statement
var cellWidth = ... // some integer
var cellHeight;
switch(value){
case 50:
cellHeight = 100;
break; // do not execute other cases
case 100:
cellHeight = 50;
break;
default:
cellHeight = 30;
}

</script>
7
Functions

<html>
<head>
<script type="text/javascript">
function product(n, m)
! {
! res = m * n;
! alert("The result of the product is " + res);
! }
</script>
</head>

<body onload="product(7, 3)">



</body>
</html>

8
Classes and Objects

• JavaScript is dynamic, object-oriented and is weakly typed

• Functions are first-class objects


✦ They are objects themselves
✦ They have properties and methods, such as length and call()
✦ They can be assigned to variables, passed as arguments, returned by other
functions, and manipulated like any other object

• JavaScript classes can be declared with the keyword function()


✦ e.g., function Person(nameArg){ ... } is the declaration of the class person

• New objects of a class can be instantiated with the keyword


new
✦ e.g., var me = new Person(“Andrea Nuzzolese”);

• The fields of a class can be accessed either by obj.field or by


obj[“field”] 9
Example

function Person(param1){ // Constructor


! this.name = param1;
}

/*
* Create a new instance of the class Person.
* This instance represents me.
*/
var me = new Person(“Andrea Nuzzolese”);

alert(me.name); // Access and alert the field name

10
Prototypes

• JavaScript uses prototypes instead of classes for inheritance

• Each JavaScript function has a prototype attribute that refers to a


prototype object

• It is possible to add to the prototype attribute new methods and


properties
✦ easy to extend a library
✦ easy to extend your classes by need

11
Using prototype for methods

function Person(param1){ // Constructor


! this.name = param1;
}

/*
* Create a new instance of the class Person.
* This instance represents me.
*/
var me = new Person(“Andrea Nuzzolese”);

alert(me.name); // Access and alert the field name

/* Add the function welcome to the prototype of


* Person */
Persona.prototype.welcome = function(){
! alert(“welcome ”+this.name”!”);
}

12
Using prototype for inheritance

function Vehicle(passengers) {
this.speed = 0;
this.passengers = 0;
this.load = function(passengers) {
if(passengers > 0) {
this.passengers += passengers;
}
}
this.load(passengers);
}

function Airplane(passengers) {
this.load(passengers);
this.altitude = 0;
this.takeOff = function() {
this.speed = 100;
this.altitude = 10;
}
}

// in this way the class Airplane extends Vehicle


Airplane.prototype = new Vehicle();

13
Documen Object Model

• The Document Object Model (DOM) is a cross-platform


and language-independent convention for representing and
interacting with objects in HTML, XHTML and XML documents.

• Objects in the DOM tree can be addressed and manipulated by


using methods on the objects
WINDOW
• The public interface of a DOM History Location
is specified in its API
DOCUMENT
LINK ANCHOR

FORM
TEXT
SELECT

RADIO OPTIONS

CHECKBOX BUTTON

TEXTAREA RESET

PASSWORD SUBMIT

14
JavaScript DOM objects

15
Description of the principal objects

• Window: is the top-level object, which contains the properties


of the main window (position, size, etc.)

• Frame: represents the set of available frames in the window


• Document: represents the document with its properties and
elements

• Location: represents the URL of the current document


• History: represents the URL of the previous document
• Navigator: is the objects that contains client’s properties, such
as name, version number, installed plug-ins, etc.

16
The Document object

• window.document.title: document title

• window.document.forms: returns the list of forms available in the


document

• window.document.forms[0]: returns the first form in the


document

• window.document.forms[0].checkbox[0]: returns the first


checkbox of the first form

• window.document.forms[0].foo: returns the object named “foo”


of the first form

• window.document.images: returns the list of images available in


the document
17
Example

<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
function readText (form) {
var testVar =form.inputbox.value;
alert ("You typed: " + TestVar);}

function writeText (form) {


form.inputbox.value = "Have a nice day!"}
</SCRIPT>
</HEAD>

<BODY>
<FORM NAME="myform" ACTION="" METHOD="GET">
Enter something in the box: <BR/>
<INPUT TYPE="text" NAME="inputbox" VALUE=""/>
<INPUT TYPE="button" NAME="button1" Value="Read"
onClick="readText(this.form)"/>
<INPUT TYPE="button" NAME="button2" Value="Write“
onClick="writeText(this.form)"/>
</FORM>
</BODY>
</HTML>
18
Selectors

• document.getElementById(ID): returns the element in the


document identified by the “ID” passed as parameted

• document. getElementsByName(name): returns an array of


elements with a name attribute whose value matches that of the
parameter

• document.getElementsByTagName(tagname): returns an array of


elements whose tag name matches the parameter

• document.getElementsByClassName(classname): gets a collection


of element(s) based on their shared class name attribute

19
Example


<SCRIPT LANGUAGE="JavaScript">
var mainContentEl = document.getElementById("mainContent");
var recommendations =
document.getElementsByClassName("recommendation");
var advertisements =
document.getElementsByName("advertisement");
var documentDivs =
document.getElementsByTagName("div");
</SCRIPT>
</HEAD>
<BODY>
<DIV id="mainContent"> some content </DIV>
<DIV class="recommendation"> recommendation 1 </DIV>
<DIV class="recommendation"> recommendation 2 </DIV>
<DIV id="footnote_left" name="advertisement"> ... </DIV>
<DIV id="footnote_right" name="advertisement">
...
</DIV>
...
20
Ajax

• Is an acronym that stands for Asynchronous JavaScript and XML

• Is not a new programming language, but a new way to use existing


standards

• Is the art of exchanging data with a server, and update parts of a


web page - without reloading the whole page

• Is a group of interrelated web development techniques used on


the client-side to create asynchronous web applications

• In JavaScript Ajax interactions are available via the objects


XMLHttpRequest (Mozilla-based browsers) and ActiveXObject
(IE)

21
Ajax architecture

22
Client-server activities without Ajax

23
Client-server activities with Ajax

24
Ajax interactions

• JavaScript + Ajax interactions are based on 4 steps


✦ Creation of the Ajax object (XMLHttpRequest or ActiveXObject)
✦ Request initialization
✦ Request sending
✦ Response management

25
Creation of the Ajax object

if (window.XMLHttpRequest) // Mozilla, Safari,...


{
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
http_request.overrideMimeType('text/xml');
}
else if (window.ActiveXObject) // Internet Explorer
{
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {…}
}
}
26
Request initialization

/*
* The initialization of http_request.onreadystatechange
* allows to specify the function that will manage (see slide
* about request management) the response
*/
http_request.onreadystatechange = nameOfTheFunction;

/*
* The http_request.open opens a connection with a server.
*
* The first parameter specifies the type of HTTP request.
* The second parameter specifies the destination address of
* the request.
* The third parameter is a boolean value that specifies if the
* request should be performed asynchronously (true)
* synchronously (false).
*/
http_request.open('GET','http://www.example.org/some.file',true);
27
Request sending

/*
* Request sending with HTTP GET methods.
* With HTTP GET methods the actual parameter of
* http_request.send is null because the values are passed
* to the server through the URL when the connection is opened.
*/
http_request.send(null);

/*
* Request sending with HTTP POST methods.
* With HTTP GET methods the parameters to send
* to the server are passed as a query-string containing
* couples of attribute=value separated by &.
*/
http_request.send(name=value&othername=othervalue&so=on);

/* Instead of a query-string, a different type (MIME type) can be


* specified to be sent to the server. */

http_request.setRequestHeader('Content-Type', 'multipart/form-data');
28
Request management (1)

/*
* In http_request.onreadystatechange we specified the function
* responsible for the request management. This usually works
* checking the HTTP status code returned by the request.
*/
var manageResponse = funtion() {
if (http_request.status == 200) {
! // perfect!
}
else {
! // there was a problem with the request,
! // for example the response may be a 404 (Not Found)
! // or 500 (Internal Server Error) response codes
}

http_request.onreadystatechange = manageResponse;

/*
29
HTTP status codes

• It is possible to manage any HTTP status code by specifying an


action for each of them
✦ 1xx: Informational ✦ 4xx: Client error
✴ 100: Continue ✴ 400: Bad request
✴ 101: Switching protocol ✴ 401: Unauthorized
✦ 2xx: Successful ✴ 403: Forbidden
✴ 200: OK
✴ 404: Not found
✴ 201: Created
✴ 405: Method not allowed
✴ 204: No content
✴ ...
✴ ... ✦ 5xx: Server error
✴ 500: Internal server error
✦ 3xx: Redirection
✴ 501: Not implemented
✴ 301: Moved permanently
✴ 303: See Other ✴ 502: Bad gateway

✴ ... ✴ 503: Service anavailable

✴ ...
30
Reading the response

• If the status code is 200 (OK) the response sent by the server
can be read

• Two methods allow to read responses


✦ http_request.responseText: returns the response as a plain text
✦ http_request.responseXML: returns the response as a
XMLDocument, which implements the XML DOM

31
Example

// initialize the XMLHttpRequest object request


  myXMLHTTPRequest = new XMLHttpRequest();

// open a connection in HTTP GET


  myXMLHTTPRequest.open("GET", "example1.xml", false);

// configure the response management


http_request.onreadystatechange = funtion() {
if (http_request.status == 200) {
//read the response
  xmlDoc = myXMLHTTPRequest.responseXML;
//get any needed information
  fragment = xmlDoc.getElementsbyId(“content”).item(0);
// modify the current document
  document.getElementById(“area1")
.appendChild(fragment);
}
else {
! alert(“An error occurred.”);
}
}
// send the request
 myXMLHTTPRequest.send(null);
32
Response types

• Plain text responses are human-readable but not machine-


processable

• XML responses are machine-processable but not human-readable


but

• XML responses can be very long in terms of bytes due to


verbosity of the XML syntax

• Other response types (MIME type) can be requested to the


server specifying the Accept header
✦ e.g., http_request.setRequestHeader('Accept', 'text/html');

33
JSON

• The JavaScript Object Notation (JSON) is a lightweight


data-interchange format

• It is a text-based open standard designed for human-readable and


machine-processable data interchange

• It is derived from JavaScript and allows to represent and


exchange simple data structures and associative arrays, and
objects

• Despite its relationship to JavaScript, it is language-independent,


with parsers available for many languages.

34
JSON data structures

• JSON is built on two structures:


✦ A collection of name/value pairs. In various languages, this is realized as an
object, record, struct, dictionary, hash table, keyed list, or associative array.
✦ An ordered list of values. In most languages, this is realized as an array,
vector, list, or sequence.

• These are universal data structures.Virtually all modern


programming languages support them in one form or another.

• It makes sense that a data format that is interchangeable with


programming languages also be based on these structures.

35
JSON object

• It is an unordered set of name/value pairs

• It begins with { (left brace) and ends with } (right brace)

• Each name is followed by : (colon) and the name/value pairs are


separated by , (comma)

36
Example

/*
* This is an example of JSON object.
* It is a collection of comma-separated name:value pairs.
* A value can be a string, a number, a boolean, an
* object (see address), an array, and a null.
*/
{
"firstName": "John",
"lastName" : "Smith",
"age" : 25,
"address" :
{
"streetAddress": "21 2nd Street",
"city" : "New York",
"state" : "NY",
"postalCode" : "10021"
}
}

37
JSON array

• It is an ordered collection of values

• It begins with [ (left bracket) and ends with ] (right bracket)

• Values are separated by , (comma)

38
{
"firstName": "John",
"lastName" : "Smith",
"age" : 25,
"address" :
{
"streetAddress": "21 2nd Street",
"city" : "New York",
"state" : "NY",
"postalCode" : "10021"
},
\\ Here we add an array containing other objects as values
"phoneNumber":
[
{
"type" : "home",
"number": "212 555-1234"
},
{
"type" : "fax",
"number": "646 555-4567"
}
]
} 39
JSON value

• It can be a string, a number, a boolean, an object (see address), an


array, and a null

40
Hot to manage JSON with JavaScript and Ajax

• JSON can be requested to a server by specifying the right MIME


type in the Accept header of the Ajax request
✦ http_request.setRequestHeader('Accept, 'application/json');

• JSON can be parsed from the response text


✦ var contactJSON = JSON.parse(http_request.responseText);

• Values in the JSON can be accessed as fields


✦ var contactFirstName = contactJSON.firstName;
✦ var contactLastName = contactJSON.lastName;
✦ var contactStreet = contactJSON.address.streeAddress;
✦ var contactFirstPhone = contactJSON.phoneNumber[0].number;

41
Example
// initialize the XMLHttpRequest object request
  myXMLHTTPRequest = new XMLHttpRequest();

// set the JSON MIME type in the Accept header


http_request.setRequestHeader('Accept, 'application/json');
// open a connection in HTTP GET
  myXMLHTTPRequest.open("GET", "http://contact-list.foo?id=5", true);

// configure the response management


http_request.onreadystatechange = funtion() {
if (http_request.status == 200) {
//read the response and parse the JSON
  var contact = JSON.parse(http_request.responseText);
//get any needed information
  var contactfirstName = contact.firstName
//create a new text node in the document
var contentNode = document.createTextNode(contactfirstName);
//add the text node to a specific element
  document.getElementById(“contact5")
.appendChild(contentNode);
}
else {
! alert(“An error occurred.”);
}
}
// send the request
 myXMLHTTPRequest.send(null); 42
jQuery

• It is a cross-browser JavaScript library designed to simplify the


client-side scripting of HTML

• It was released in January 2006 at BarCamp NYC by John Resig

• Used by over 52% of the 10,000 most visited websites

• jQuery's syntax is designed to make it easier to navigate a


document, select DOM elements, create animations, handle
events, and develop Ajax applications

• It works in the same way in all browsers

43
jQuery’s features

• DOM element selections

• DOM traversal and modification (including support for CSS 1-3)

• DOM manipulation based on CSS selectors that uses node elements name and node
elements attributes (id and class) as criteria to build selectors

• Events

• Effects and animations

• Ajax

• Extensibility through plug-ins

• Utilities - such as user agent information, feature detection

• Compatibility methods that are natively available in modern browsers but need
fallbacks for older ones - For example the inArray() and each() functions.

• Cross-browser support
44
Including jQuery

• The jQuery library is a single JavaScript file, containing all of its


common DOM, event, effects, and Ajax functions

• It can be included within a web page by linking to a local copy, or


to one of the many copies available from public server

<HTML>
<HEAD>
...
<SCRIPT type="text/javascript" src="jquery.js"></SCRIPT>
..
</HEAD>
<BODY>
...
</BODY>
</HTML>

45
jQuery Vs. JavaScript

• Hide divs with pure JavaScript


divs = document.getElementByTagName(‘div’);

for (i = 0; i < divs.length; i++) {


divs[i].style.display = ‘none’;
}

• Hide divs with jQuery

$(“div”).hide();

46
jQuery selectors

• $(“#content”) get element with id content

• $(“li:first”) get first list item

• $(“tr:odd”) get odd numbered table rows

• $(“a[target=_blank]”) get all links who’s target is “_blank”

• $(“form[id^=step]”) get all forms who’s id starts with “step”

47
Attributes (1)

• .addClass()
✦ Manages Class Attribute, CSS
✦ Adds the specified class(es) to each of the set of matched elements.

• .attr()
✦ Manages general attributes
✦ Get or set the value of an attribute for the first element in the set of
matched elements.

• .hasClass()
✦ Manages Class Attribute, CSS
✦ Determine whether any of the matched elements are assigned the given
class.

• .html()
✦ Manages DOM Insertion, Inside
✦ Get or set the HTML content of48 the first element in the set of matched
Attributes (2)

• .prop()
✦ Manages general attributes
✦ Get or set the value of a property for the first element in the set of
matched elements.

• .removeAttr()
✦ Manages general attributes
✦ Remove an attribute from each element in the set of matched elements.

• .removeClass()
✦ Manages class attributes and CSS
✦ Remove a single class, multiple classes, or all classes from each element in
the set of matched elements.

• .removeProp()
✦ Manages general attributes
✦ Remove a property for the set of
49 matched elements.
Attribute (3)

• .toggleClass()
✦ Manages Class Attribute, CSS
✦ Add or remove one or more classes from each element in the set of
matched elements, depending on either the class's presence or the value of
the switch argument.

• .val()
✦ Manages forms and general attributes
✦ Get or set the current value of the first element in the set of matched
elements

50
Example

/*
* add the class enabled_contact to the element with ID contact5
*/
$(“#contact5”).addClass(“enabled_ contact”);

/*
* remove the class disabled_contact to the element with ID contact5
*/
$(“#contact5”).removeClass(“disabled_ contact”);

/*
* copy the html content from the first element in the list
* to the element with ID contact5
*/
$(“#contact5”).html($(“li:first”).html());

/*
* add solid red border with a 3px line to the elements
* of the class frame
*/
$(".frame").css("border","3px solid red");

51

You might also like