SlideShare a Scribd company logo
Javascript, DOM, browsers 
  and frameworks basics


   NetSeven HQ - 29 March 2011

           Simone Fonda
         fonda@netseven.it
Abstract

Javascript basics (types, objects, .prototype, arguments,
scope)

Browsers (history, what they do)

DOM (definition, example, history, scripting)

Javascript Frameworks (examples)

jQuery (chaining, .data(), events, onload/ready, bind vs live)



Advanced topics (not covered)
Javascript

  .. basics
JAVASCRIPT - types .

typeof "oh hai" // "another string", "", ''
> "string"

typeof 31512 // 1, 2, 3, .. 10.15, 3.1415, .. 134.1251 ..
> "number"

typeof true // false, 1 == 1, 1&&1, !1, !!!!!!0
> "boolean"

function f() { alert('oh hai'); }
typeof f
> "function"

typeof antani
> "undefined"
JAVASCRIPT - types ..

typeof [] // [1, 2], ["oh", "hai"], [1, true, function() { alert('oh hai')}]
> "object"

var array = [true, false, 1, 3.14, 1/3, function() {alert('oh hai')}]
for (i in array) { console.log(i, array[i], typeof(array[i])) }
> 0 true boolean
> 1 false boolean
> 2 1 number
> 3 3.14 number
> 4 0.3333333333333333 number
> 5 function () {alert('oh hai');} function
JAVASCRIPT - types ...

typeof {} // {a:1, b:2}, {a:"oh", b:"hai"}, {function() { alert('oh hai')}
> "object"

var ob = {a: true, b: false, c:1, d: 3.14, XYZ: 1/3, fufu: function()
{ alert('oh hai') }}
for (i in ob) { console.log(i, ob[i], typeof(ob[i])) }
> a true boolean
> b false boolean
> c 1 number
> d 3.14 number
> XYZ 0.3333333333333333 number
> fufu function () { alert('oh hai'); } function
JAVASCRIPT - types .... objects?

var ob = {a: true, b: false, c:1, d: 3.14}
ob.d // or use ob['d']
> 3.14

var ar = [1, 2, 3/2]
ar.length // an array!
>3

'oh hai'.length // a string !
>6

var fu = function() { alert('oh hai') }
fu.toString()
> "function() { alert('oh hai') }"
JAVASCRIPT - object's .prototype

String.prototype.evve = function() { return this.replace(/r/g, 'V') }
"orrore un ramarro marrone".evve()
> "oVVoVe un VamaVVo maVVone"


- "Everything is an object"
- "Objects can be extended"
- "There's no such thing as Class"
JAVASCRIPT - functions' arguments .

Overload?

function add(a, b, c, d) { return a+b+c+d; }
function add(a, b, c) { return a+b+c; }
function add(a, b) { return a+b; }

add(1, 2)
> .. == 3 ??

add(1, 2, 3)
> .. == 6 ??

add(1, 2, 3, 4)
> .. == 10 ??
JAVASCRIPT - functions' arguments ..

Overload? NO! Last definition prevails!

function add(a, b, c, d) { return a+b+c+d; }
function add(a, b, c) { return a+b+c; }
function add(a, b) { return a+b; }

add(1, 2)
>3

add(1, 2, 3) // 3rd argument is just ignored ..
>3

add(1, 2, 3, 4) // 3rd and 4th arguments are ignored
>3
JAVASCRIPT - functions' arguments ...

Overload? Kind of, use arguments !

function add() {
  var r=0;
  for (i=0; i<arguments.length; i++)
     r += arguments[i];
  return r;
}

add(1, 2, 3, 4, 5, 6, 7)
> 28

add(1, 3/5, Math.PI, Math.pow(2, 1.55), Math.sqrt(2), -5)
> 4.083977607854139
JAVASCRIPT - functions' arguments ....

Overload? Kind of, use arguments !

function add() {
  var r=0;
  for (i=0; i<arguments.length; i++)
     r += arguments[i];
  return r;
}

add(1, 2, 3, 4, 'oh hai')
> .. == ?

add('oh hai', 2, 3, 4, 5)
> .. == ?
JAVASCRIPT - functions' arguments .....

Overload? Kind of, use arguments !

function add() {
  var r=0;
  for (i=0; i<arguments.length; i++)
     r += arguments[i];
  return r;
}

add(1, 2, 3, 4, 'oh hai') // + used for string concatenation as soon
> "10oh hai"              // as a string is... added
add('oh hai', 2, 3, 4, 5) // r is initially equal to 0 (the number)
> "0oh hai2345"
JAVASCRIPT - scope .

Javascript (as a language) does NOT have a global scope..
.. it comes from the browser: window (and it's an object!!)


<script> // outside everything (objects/functions)
var foo = "oh hai";
</script>

window.foo = "oh hai"; // directly attached to window object
window['foo'] = "oh hai";

function doSomething() { // in a object/function without var
  foo = "oh hai";
}
JAVASCRIPT - scope ..

var foo = 'oh hai';
function doSomething() {
   var foo = 'Goodbye';
   return foo;
}
console.log(foo, doSomething())
> .. == ??

var foo = 'oh hai';
function doSomething() {
   foo = 'Goodbye';
   return foo;
}
console.log(foo, doSomething())
> .. == ??
JAVASCRIPT - scope ...

var foo = 'oh hai';
function doSomething() {
  var foo = 'Goodbye';
  return foo;
}
console.log(foo, doSomething()) // global foo remains the same
> oh hai Goodbye

var foo = 'oh hai';
function doSomething() {
  foo = 'Goodbye';
  return foo;
}
console.log(foo, doSomething()) // foo hasn't changed yet!! :P
> oh hai Goodbye // next console.log() "Goodbye Goodbye"!
Browsers

retrieving, presenting, and traversing information
resources on the World Wide Web, since 1980s.
Browsers - a little bit of history .

The history of the Web browser dates back in to the late 1980s,
when a variety of technologies laid the foundation for the first
Web browser, WorldWideWeb, by Tim Berners-Lee in 1991.
That browser brought together a variety of existing and new
software and hardware technologies.

Ted Nelson and Douglas Engelbart developed the concept
of hypertext long before Berners-Lee and CERN. It became the
core of the World Wide Web. Berners-Lee does acknowledge
Engelbart's contribution.
Browsers - a little bit of history ..

The introduction of the NCSA Mosaic Web browser in 1993 – one of the first graphical
Web browsers – led to an explosion in Web use. Marc Andreessen, the leader of the
Mosaic team at the National Center for Supercomputing Applications (NCSA), soon
started his own company, named Netscape, and released the Mosaic-
influenced Netscape Navigator in 1994, which quickly became the world's most popular
browser, accounting for 90% of all Web use at its peak (see usage share of web
browsers). Microsoft responded with its browser Internet Explorer in 1995 (also heavily
influenced by Mosaic), initiating the industry's first browser war. By bundling Internet
Explorer with Windows, Microsoft was able to leverage its dominance in the operating
system market to take over the Web browser market; Internet Explorer usage share
peaked at over 95% by 2002. The usage share of Internet Explorer has declined from
over 62.1% in January 2010 to 56.0% in January 2011 according to Net
Applications. In February 2011 its share has increased again to 56.8%.
Browsers - a little bit of history ...
Opera first appeared in 1996; although it has never achieved widespread use, it holds a stable share
of in between 2.1% and 2.4%, and it has a substantial share of the fast-growingmobile phone Web
browser market, being preinstalled on over 40 million phones. It is also available on several
other embedded systems, including Nintendo's Wii video game console. In 1998, Netscape launched
what was to become the Mozilla Foundation in an attempt to produce a competitive browser using
the open source software model. That browser would eventually evolve into Firefox, which
developed a respectable following while still in the beta stage of development; shortly after the
release of Firefox 1.0 in late 2004, Firefox (all versions) accounted for 7.4% of browser use. The
Firefox usage share has slowly declined in 2010, from 24.4% in January to 21.7% in February 2011.
Apple's Safari had its first beta release in January 2003; it has a dominant share of Apple-based Web
browsing, having risen from 4.5% usage share in January 2010 to 6.7% in February 2011. Its
rendering engine, called WebKit, is also running in the standard browsers of several mobile phone
platforms, including Apple iOS, Google Android, Nokia S60 and PalmwebOS. The most recent
major entrant to the browser market is Google's WebKit-based Chrome, first released in September
2008. Its market share has quickly risen; its usage share has doubled from 5.2% in January 2010 to
10.9% in February 2011, but in recent months its growth is not as drastic as before.
Browsers - a little bit of history ....
The primary purpose of a web browser is to bring information resources to the user. This process begins when the user inputs a
Uniform Resource Identifier (URI), for example http://en.wikipedia.org/, into the browser. The prefix of the URI determines how
the URI will be interpreted. The most commonly used kind of URI starts with http: and identifies a resource to be retrieved over
the Hypertext Transfer Protocol (HTTP). Many browsers also support a variety of other prefixes, such as https: for HTTPS, ftp:
for the File Transfer Protocol, and file: for local files. Prefixes that the web browser cannot directly handle are often handed off
to another application entirely. For example, mailto: URIs are usually passed to the user's default e-mail application and news:
URIs are passed to the user's default newsgroup reader. In the case of http, https, file, and others, once the resource has been
retrieved the web browser will display it. HTML is passed to the browser's layout engine to be transformed from markup to an
interactive document. Aside from HTML, web browsers can generally display any kind of content that can be part of a web
page. Most browsers can display images, audio, video, and XML files, and often have plug-ins to support Flash applications
and Java applets. Upon encountering a file of an unsupported type or a file that is set up to be downloaded rather than
displayed, the browser often prompts the user to save the file to disk or identify a program that can open it. Interactivity in a web
page can also be supplied by JavaScript, which usually does not require a plugin. JavaScript can be used along with other
technologies to allow "live" interaction with the web page's server via Ajax. In the most advanced browsers, JavaScript
programs can produce interactive 2D graphics using the canvas API and fully rendered 3D graphics using WebGL. Information
resources may contain hyperlinks to other information resources. Each link contains the URI of a resource to go to. When a link
is clicked, the browser navigates to the resource indicated by the link's target URI, and the process of bringing content to the
user begins again. Available web browsers range in features from minimal, text-based user interfaces with bare-bones support
for HTML to rich user interfaces supporting a wide variety of file formats and protocols. Browsers which include additional
components to support e-mail, Usenet news, and Internet Relay Chat (IRC), are sometimes referred to as "Internet suites"
rather than merely "web browsers". All major web browsers allow the user to open multiple information resources at the same
time, either in different browser windows or in different tabs of the same window. Major browsers also include pop-up blockers
to prevent unwanted windows from "popping up" without the user's consent. Most web browsers can display a list of web pages
that the user has bookmarked so that the user can quickly return to them. Bookmarks are also called "Favorites" in Internet
Explorer. In addition, all major web browsers have some form of built-in web feed aggregator. In Mozilla Firefox, web feeds are
formatted as "live bookmarks" and behave like a folder of bookmarks corresponding to recent entries in the feed. In Opera, a
more traditional feed reader is included which stores and displays the contents of the feed. Furthermore, most browsers can be
extended via plug-ins, downloadable components that provide additional features. Early web browsers supported only a very simple
version of HTML. The rapid development of web browsers led to the development of non-standard dialects of HTML, leading to problems
with interoperability. Modern web browsers support a combination of standards-based and de facto HTML and XHTML, which should be
rendered in the same way by all browsers.
Browsers - what they do for you
- Downloads the requested page
- Downloads included assets (css, javascript, images, ..)

... progressive content loading ...

- Elements size
- Float, positioning

- User interaction (keyboard, mouse)
- Handles events (keyboard, mouse, ajax, timers, ..)

- Creates a DOM representation to interact with .......... ??
DOM

the Document Object Model
DOM : Document Object Model .


The Document Object Model (DOM) is an
application programming interface (API) for
valid HTML and well-formed XML documents.

It defines the logical structure of documents and
the way a document is accessed and
manipulated
DOM : Document Object Model ..


<html>
  <head>
    <title>Oh hai</title>
  </head>
  <body>
    <span></span>
    <div>Immagine:
       <img src=''>
    </div>
  </body>
<html>
DOM : Document Object Model ...
JavaScript was released by Netscape Communications in
1996 within Netscape Navigator 2.0. Netscape's competitor,
Microsoft, released Internet Explorer 3.0 later the same year
with a port of JavaScript called JScript. JavaScript and JScript
let web developers create web pages with client-side
interactivity. The limited facilities for detecting user-generated
events and modifying the HTML document in the first
generation of these languages eventually became known as
"DOM Level 0" or "Legacy DOM". No independent standard
was developed for DOM Level 0, but it was partly described in
the specification of HTML4. For example, a form input element
could be accessed as either "document.formName.
inputName" or "document.forms[0].elements[0]". The Legacy
DOM enabled client-side form validation and the popular
"rollover" effect.
DOM : Document Object Model ....

In 1997, Netscape and Microsoft released version 4.0 of
Netscape Navigator and Internet Explorer, adding support for
Dynamic HTML (DHTML), functionality enabling changes to
a loaded HTML document. The Intermediate DOMs enabled
the manipulation of Cascading Style Sheet (CSS) properties
which influence the display of a document. They also
provided access to a new feature called "layers" via the
"document.layers" property (Netscape Navigator) and the
"document.all" property (Internet Explorer). Because of the
fundamental incompatibilities in the Intermediate DOMs,
cross-browser development required special handling for
each supported browser.
DOM : Document Object Model .....
The World Wide Web Consortium (W3C), founded in 1994 to promote open
standards for the World Wide Web, brought Netscape Communications and
Microsoft together with other companies to develop a standard for browser
scripting languages, called "ECMAScript". After the release of ECMAScript, W3C
began work on a standardized DOM. The initial DOM standard, known as "DOM
Level 1", was recommended by W3C in late 1998. About the same time, Internet
Explorer 5.0 shipped with limited support for DOM Level 1. DOM Level 1
provided a complete model for an entire HTML or XML document, including
means to change any portion of the document. Non-conformant browsers such
as Internet Explorer 4.x and Netscape 4.x were still widely used as late as 2000.
DOM Level 2 was published in late 2000. It introduced the "getElementById"
function as well as an event model and support for XML namespaces and CSS.
DOM Level 3, the current release of the DOM specification, published in April
2004, added support for XPath and keyboard event handling, as well as an
interface for serializing documents as XML. By 2005, large parts of W3C DOM
were well-supported by common ECMAScript-enabled browsers, including
Microsoft Internet Explorer version 6 (2001), Opera, Safari and Gecko-based
browsers (like Mozilla, Firefox, SeaMonkey and Camino).
DOM scripting .
// Change the style of an H1 tag
if (document.getElementsByTagName('h1').length > 0) {
    h = document.getElementsByTagName('h1')[0];
    h.style.color = 'red';
    h.style.fontFamily = 'Arial';
    h.style.fontWeight = 'bold';
    h.style.borderStyle = 'solid';
    h.style.borderColor = '#c00';
    h.style.borderWidth = '1px';
}
DOM scripting ..
window.onload = function() { // Call when document is loaded
  alert('oh hai');
}



What if we need to call more than a single function?
DOM scripting ...
window.onload = function() { // Call when document is loaded
  alert('oh hai');
}

function addLoadEvent(func) { // ADD a function to call when..
  var oldonload = window.onload;
  if (typeof window.onload != 'function') {
      window.onload = func;
  } else {
      window.onload = function() {
         oldonload();
         func();
      }
  }
}
addLoadEvent(function() { alert('oh hai') });
DOM scripting ....
// call a function when user clicks on the first A inside a
// certain container ..
var container = document.getElementById('containerId');
if (!container) { return; }
if (container.getElementsByTagName('a').length > 0) {
    var a = container.getElementsByTagName('a')[0];
    a.onclick= function() { doSomething() } ;
}
DOM scripting .....
// Get x,y coordinates from a mouse click event
function doSomething(e) {
   var posx = 0, posy = 0;
   if (!e) var e = window.event; // some passes e, some dont
   if (e.pageX || e.pageY) {
       posx = e.pageX; // safari and opera, NOT IE
       posy = e.pageY;
   } else if (e.clientX || e.clientY) {
       posx = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
       posy = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
   }
   // Use posx and posy ....
}
DOM scripting ......
function getData() {
  var xhr;
  try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); } // Internet Explorer
  catch (e) {
     try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } // Another IE
     catch (e2) {
         try { xhr = new XMLHttpRequest(); } // Firefox, Safari, ..
         catch (e3) { xhr = false; }
     }
  }
  xhr.onreadystatechange = function() { // Called quite often.. 1, 2, 3, 4 ..
     if (xhr.readyState == 4) { // 4 = transaction finished
         if (xhr.status == 200) document... = "Received:" + xhr.responseText;
         else document... = "Error code " + xhr.status;
     }
  };
  xhr.open(GET, "data.txt", true); // Start the connection!
  xhr.send(null);
}
DOM scripting .......
document.createElement()        event.target
document.createTextNode()       event.currentTarget
document.createAttribute()      event.bubbles
....                            ....
node.nodeName                   stylesheet.href
node.firstChild                 stylesheet.item
node.previousSibling            stylesheet.insertRule
node.attributes                 stylesheet.deleteRule
node.insertBefore()             ....
node.replaceChild()             cssrule.cssText
node.hasChildNodes()            cssrule.parentRule
node.replaceChild()             cssrule.type
node.hasAttributes()            ....
....                            nodeIterator.nextNode()
object.getAttribute()           nodeInterator.previousNode()
object.setAttribute()           ....
object.getElementsByTagName()   range.setStart()
....                            range.setEnd()
object.addEventListener()       range.setStartBefore()
object.dispatchEvent()          range.setEndBefore()
                                range.cloneContents()
Javascript Frameworks

    TO THE RESCUE!
Javascript frameworks to the rescue! 

Cross browser

DOM scripting made easy (selectors, events, ..)

Ajax made easy (get, post, ..)

More goodies (each(), map(), grep(), ...)

Spice up your page with effects (slideUp(), hide(1000), ..)

Large community (sharing problems and solutions)

Tons of available scripts/plugins (too many??)
Javascript frameworks to the rescue! .
if (document.getElementsByTagName('h1').length > 0) {
    h = document.getElementsByTagName('h1')[0];
    h.style.color = 'red';
    h.style.borderStyle = 'solid';
    h.style.borderColor = '#c00';
    h.style.borderWidth = '1px';
}


Using jQuery for Selectors:
$('h1:first').css({color: 'red', border: '1px solid #c00'})


$('h1') ~= document.getElementsByTagName('h1')
$('#foo') ~= document.getElementById('foo')
Javascript frameworks to the rescue! ..
window.onload = function() { // Call when document is loaded
  alert('oh hai');
}


Using jQuery for events:
$(document).ready(function() {
    alert('oh hai');
});

As many as you want, for free!



(Not exactly the same behaviour.. more on this later.)
Javascript frameworks to the rescue! ...
// call a function when click on the first A inside a certain
// container ..
var container = document.getElementById('containerId');
if (!container) { return; }
if (container.getElementsByTagName('a').length > 0) {
    var a = container.getElementsByTagName('a')[0];
    a.onclick = function() { doSomething() } ;
}


Using jQuery for selectors and events:
$('#containerId a:first').click(function() { doSomething() });
Javascript frameworks to the rescue! ....
function getData() {
   var xhr;
   try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); } // Internet Explorer
   catch (e) {
      try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } // Another IE
      catch (e2) {
          try { xhr = new XMLHttpRequest(); } // Firefox, Safari, ..
          catch (e3) { xhr = false; }
      }
   }
   xhr.onreadystatechange = function() { // Called quite often.. 1, 2, 3, 4 ..
      if (xhr.readyState == 4) { // 4 = transaction finished
          if (xhr.status == 200) document... = "Received:" + xhr.responseText;
          else document... = "Error code " + xhr.status;
      }
   };
  xhr.open(GET, "data.txt", true); // Start the connection!
  xhr.send(null);
}


Using jQuery for ajax:
$.ajax({
  url: "data.txt",
  success: function(data) { $('#foo').val(data); }
});
jQuery

random tips and tricks
jQuery .
Chaining: jQuery returns itself (sort of ......)


$('#foo'); // == jQuery object
$('#foo').css({border: '1px solid red'}); // == jQuery object
$('#foo').click(function() { alert('Nice click') }); // == jQuery object
$('#foo').hover(function() { alert('Over!') }); // == jQuery object


              ..... all of them are jQuery objects .....
jQuery .
Chaining: jQuery returns itself (sort of ......)


$('#foo'); // == jQuery object
$('#foo').css({border: '1px solid red'}); // == jQuery object
$('#foo').click(function() { alert('Nice click') }); // == jQuery object
$('#foo').hover(function() { alert('Over!') }); // == jQuery object


              ..... all of them are jQuery objects .....

$('#foo')
   .css({border: '1px solid red'})
   .click(function() { alert('Nice click') })
   .hover(function() { alert('Over!')}); // == jQuery object
jQuery ..
.data(): linking custom data to elements


$('#foo').data('uri', 'http://my_precious_URI'); // storing
$('#foo').data('type', 'IIP image'); // storing


if ($('#foo').data('type') === 'IIP image')) // retrieving
    uri = $('#foo').data('uri');


$('#foo').removeData(); // deleting
jQuery ...
events: onload? document ready? Which order??

<html>
  <script src='http://code.jquery.com/jquery-1.5.js'></script>
  <script>
     $(document).ready(function() {
         console.log('document is ready');
     });
     window.onload = function() {
         console.log('window is loaded ');
     }
     console.log('This is executed');
  </script>
  <body>
  </body>
</html>
jQuery ...
events: onload? document ready? Which order??

$(document).ready(): called BEFORE window.onload !! DOM
ready to be manipulated (hide, addclass, remove..)

window.onload(): all the assets has been loaded (images,
banners, ..)


Answer:
> This is executed
> document is ready
> window is loaded
jQuery ...
events: onload? document ready? Which order??

<html>
  <script src='http://code.jquery.com/jquery-1.5.js'></script>
  <script>
     $('#foo').html("Goodbye!");
  </script>
  <body>
     <div id='foo'>Oh hai!</div>
  </body>
</html>


page == ??
jQuery ...
events: onload? document ready? Which order??

<html>
  <script src='http://code.jquery.com/jquery-1.5.js'></script>
  <script>
     $('#foo').html("Goodbye!");
  </script>
  <body>
     <div id='foo'>Oh hai!</div>
  </body>
</html>


page == "Oh hai!": the div does not exist yet .... :(
jQuery ...
events: onload? document ready? Which order??

<html>
  <script src='http://code.jquery.com/jquery-1.5.js'></script>
  <script>
     $(document).ready(function() {
         $('#foo').html("Goodbye!");
     });
  </script>
  <body>
     <div id='foo'>Oh hai!</div>
  </body>
</html>

page == "Goodbye!"
jQuery ....
events: bind() versus live()


                     $('.foo').click(function() { })
                                   ==
                 $('foo').bind('click', function() { })


                                 BUT


                 $('foo').bind('click', function() { })
                                    !=
                 $('foo').live('click', function() { });
jQuery ....
events: bind() versus live()

<html>
  <script src='http://code.jquery.com/jquery-1.5.js'></script>
  <script>
     $('div.foo').click(function() {
         $('body').append("<div class='foo'>... Oh hai!!</div>")
     });
  </script>
  <body><div class='foo'>Oh hai!</div></body>
</html>

What does this do? ..
jQuery ....
events: bind() versus live()

<html>
  <script src='http://code.jquery.com/jquery-1.5.js'></script>
  <script>
     $('div.foo').click(function() {
         $('body').append("<div class='foo'>... Oh hai!!</div>")
     });
  </script>
  <body><div class='foo'>Oh hai!</div></body>
</html>

What does this do? .. NOTHING! div doesnt exist yet!!! ;)
jQuery ....
events: bind() versus live()

<html>
  <script src='http://code.jquery.com/jquery-1.5.js'></script>
  <script>
     $(document).ready(function() {
         $('div.foo').click(function() {
             $('body').append("<div class='foo'>... Oh hai!!</div>")
         });
     });
  </script>
  <body><div class='foo'>Oh hai!</div></body>
</html>

What does this do? ..
jQuery ....
events: bind() versus live()

<html>
  <script src='http://code.jquery.com/jquery-1.5.js'></script>
  <script>
     $(document).ready(function() {
         $('div.foo').click(function() {
             $('body').append("<div class='foo'>... Oh hai!!</div>")
         });
     });
  </script>
  <body><div class='foo'>Oh hai!</div></body>
</html>

What does this do? .. adds a div.foo "... Oh hai!!" item by clicking
on the first div, the one coming from the original document.
jQuery ....
events: bind() versus live()

<html>
  <script src='http://code.jquery.com/jquery-1.5.js'></script>
  <script>
     $('div.foo').live('click', function() {
         $('body').append("<div class='foo'>... Oh hai!!</div>")
     });
  </script>
  <body><div class='foo'>Oh hai!</div></body>
</html>

What does this do? ..
jQuery ....
events: bind() versus live()

<html>
  <script src='http://code.jquery.com/jquery-1.5.js'></script>
  <script>
     $('div.foo').live('click', function() {
         $('body').append("<div class='foo'>... Oh hai!!</div>")
     });
  </script>
  <body><div class='foo'>Oh hai!</div></body>
</html>

What does this do? .. adds a div.foo "... Oh hai!!" item by clicking
on any div.foo item!!

Even the future ones!
Advanced topics .. are you curious?
js closures ()()
js meta-programming (code which modifies code)
js timers
js events, this object and scope
js == vs ===
js eval
js using callbacks (apply, call)
js delayed script loading

HTML/js optimization to get a snappier user experience (sprites,
scripts optimizations, ..)

jQuery vs other frameworks (prototype, mootools, ..)
jQuery animations and chained animations
jQuery ajax data retrieval (JSON?)
jQuery plugins (how to build one)
That's ALL!


Download this presentaion in PDF from:
          http://bit.ly/ejLetd




            Simone Fonda
          fonda@netseven.it

More Related Content

What's hot (20)

PPTX
Javascript inside Browser (DOM)
Vlad Mysla
 
PPTX
Web Development Introduction to jQuery
Laurence Svekis ✔
 
PPTX
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...
Ayes Chinmay
 
KEY
Week 4 - jQuery + Ajax
baygross
 
PPT
Javascript: Ajax & DOM Manipulation v1.2
borkweb
 
PPTX
Internet and Web Technology (CLASS-6) [BOM]
Ayes Chinmay
 
PPTX
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
Ayes Chinmay
 
PPT
jQuery
Mohammed Arif
 
PPT
KMUTNB - Internet Programming 4/7
phuphax
 
PPT
JavaScript
Doncho Minkov
 
PPTX
Part 7
NOHA AW
 
PPT
AJAX Workshop Notes
Pamela Fox
 
PDF
Unit 4(it workshop)
Dr.Lokesh Gagnani
 
PPTX
Xml part 6
NOHA AW
 
PPTX
JavaScript and jQuery Basics
Kaloyan Kosev
 
PPTX
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Ayes Chinmay
 
PPTX
jQuery Best Practice
chandrashekher786
 
PDF
jQuery Introduction
Arwid Bancewicz
 
PDF
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
PPT
J Query Public
pradeepsilamkoti
 
Javascript inside Browser (DOM)
Vlad Mysla
 
Web Development Introduction to jQuery
Laurence Svekis ✔
 
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...
Ayes Chinmay
 
Week 4 - jQuery + Ajax
baygross
 
Javascript: Ajax & DOM Manipulation v1.2
borkweb
 
Internet and Web Technology (CLASS-6) [BOM]
Ayes Chinmay
 
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
Ayes Chinmay
 
KMUTNB - Internet Programming 4/7
phuphax
 
JavaScript
Doncho Minkov
 
Part 7
NOHA AW
 
AJAX Workshop Notes
Pamela Fox
 
Unit 4(it workshop)
Dr.Lokesh Gagnani
 
Xml part 6
NOHA AW
 
JavaScript and jQuery Basics
Kaloyan Kosev
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Ayes Chinmay
 
jQuery Best Practice
chandrashekher786
 
jQuery Introduction
Arwid Bancewicz
 
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
J Query Public
pradeepsilamkoti
 

Viewers also liked (18)

PPTX
Dom(document object model)
Partnered Health
 
PDF
學習JavaScript_Dom
俊彬 李
 
PDF
javascript objects
Vijay Kalyan
 
PPT
JavaScript Objects
Reem Alattas
 
PDF
JavaScript regular expression
Hernan Mammana
 
PPTX
Document Object Model
Mayur Mudgal
 
PPTX
Javascript validating form
Jesus Obenita Jr.
 
PPTX
Form Validation in JavaScript
Ravi Bhadauria
 
PPTX
Document object model(dom)
rahul kundu
 
PPT
DOM ( Document Object Model )
ITSTB
 
PPTX
An Introduction to the DOM
Mindy McAdams
 
PPTX
Javascript
Sun Technlogies
 
PPT
Regular Expressions
Satya Narayana
 
PPTX
Introduction to Regular Expressions
Matt Casto
 
PPT
Document Object Model
chomas kandar
 
PPTX
JavaScript APIs you’ve never heard of (and some you have)
Nicholas Zakas
 
PPTX
Maintainable JavaScript 2012
Nicholas Zakas
 
Dom(document object model)
Partnered Health
 
學習JavaScript_Dom
俊彬 李
 
javascript objects
Vijay Kalyan
 
JavaScript Objects
Reem Alattas
 
JavaScript regular expression
Hernan Mammana
 
Document Object Model
Mayur Mudgal
 
Javascript validating form
Jesus Obenita Jr.
 
Form Validation in JavaScript
Ravi Bhadauria
 
Document object model(dom)
rahul kundu
 
DOM ( Document Object Model )
ITSTB
 
An Introduction to the DOM
Mindy McAdams
 
Javascript
Sun Technlogies
 
Regular Expressions
Satya Narayana
 
Introduction to Regular Expressions
Matt Casto
 
Document Object Model
chomas kandar
 
JavaScript APIs you’ve never heard of (and some you have)
Nicholas Zakas
 
Maintainable JavaScript 2012
Nicholas Zakas
 
Ad

Similar to Javascript, DOM, browsers and frameworks basics (20)

PDF
Splash
Brendan Eich
 
ODP
Html5
mikusuraj
 
PDF
Geliyoo Browser Beta (İnternet tarayıcısı) Hakkında
Xtremcoin and Geliyoo
 
PDF
Geliyoo Browser Beta
Buray Anil
 
DOC
Tutorial Solution
vikram singh
 
PPTX
Web browsers
jahnvi tanwar
 
PDF
#1 - HTML5 Overview
iloveigloo
 
PDF
Front end for back end developers
Wojciech Bednarski
 
PPTX
HTML5 Programming
hotrannam
 
PDF
Jsf2 html5-jazoon
Roger Kitain
 
PDF
Web application development - The past, the present, the future
Juho Vepsäläinen
 
PPTX
Html5v1
Ulises Torelli
 
PPTX
Prueba ppt
Ulises Torelli
 
PDF
Red Dirt JS
Nathan Smith
 
PDF
Technology for Teachers
edfactor
 
PDF
Html5 & touch
Torbjörn Sjögren
 
DOC
Internet application unit2
MSc CST
 
PPTX
01 Introduction - JavaScript Development
Tommy Vercety
 
PPTX
HTML 5
pavrabhargav
 
Splash
Brendan Eich
 
Html5
mikusuraj
 
Geliyoo Browser Beta (İnternet tarayıcısı) Hakkında
Xtremcoin and Geliyoo
 
Geliyoo Browser Beta
Buray Anil
 
Tutorial Solution
vikram singh
 
Web browsers
jahnvi tanwar
 
#1 - HTML5 Overview
iloveigloo
 
Front end for back end developers
Wojciech Bednarski
 
HTML5 Programming
hotrannam
 
Jsf2 html5-jazoon
Roger Kitain
 
Web application development - The past, the present, the future
Juho Vepsäläinen
 
Prueba ppt
Ulises Torelli
 
Red Dirt JS
Nathan Smith
 
Technology for Teachers
edfactor
 
Html5 & touch
Torbjörn Sjögren
 
Internet application unit2
MSc CST
 
01 Introduction - JavaScript Development
Tommy Vercety
 
HTML 5
pavrabhargav
 
Ad

More from Net7 (20)

PDF
E-RIHS Heritage Hub
Net7
 
PDF
Net7 @ Master Big Data 2017
Net7
 
PPTX
Presentation of context: Web Annotations (& Pundit) during the StoM Project (...
Net7
 
PDF
iAnnotate 2016 - Demo Pundit web annotator
Net7
 
PDF
Pundit at Digital Humanities Austria 2015
Net7
 
PDF
La semantica per automatizzare una redazione web: l’esperienza di Innolabspl...
Net7
 
PDF
Pundit at DINI Jahrestagungen, 2015 "Linked Data – Vision und Wirklichkeit"
Net7
 
PDF
Muruca at DiXiT Convention 1: Technology, Software, Standards
Net7
 
PDF
Pundit workshop tutorial at DiXiT Convention 1: Technology, Software, Standards
Net7
 
PDF
Pundit at DiXiT Convention 1: Technology, Software, Standards
Net7
 
PDF
Trend Analysis sui Social Network - I risultati del progetto SenTaClAus
Net7
 
PDF
Word Embedding e word2vec: Introduzione ed Esperimenti Preliminari
Net7
 
PDF
Social Media Analysis... according to Net7
Net7
 
PDF
Io sono qui per voi - Giulio Andreini
Net7
 
PDF
C'è semantica in questo web
Net7
 
PDF
Rethinking the Role of SSH - Culture and Creativity
Net7
 
PDF
Pundit at 3rd DBpedia Community Meeting 2015
Net7
 
PDF
Lod portal and pundit @ Humanities Hack london2014
Net7
 
PDF
Looking at Words through Images - Presentation at CASVA, National Gallery of ...
Net7
 
PPTX
Looking at Words through Images - Presentation at CASVA, National Gallery of ...
Net7
 
E-RIHS Heritage Hub
Net7
 
Net7 @ Master Big Data 2017
Net7
 
Presentation of context: Web Annotations (& Pundit) during the StoM Project (...
Net7
 
iAnnotate 2016 - Demo Pundit web annotator
Net7
 
Pundit at Digital Humanities Austria 2015
Net7
 
La semantica per automatizzare una redazione web: l’esperienza di Innolabspl...
Net7
 
Pundit at DINI Jahrestagungen, 2015 "Linked Data – Vision und Wirklichkeit"
Net7
 
Muruca at DiXiT Convention 1: Technology, Software, Standards
Net7
 
Pundit workshop tutorial at DiXiT Convention 1: Technology, Software, Standards
Net7
 
Pundit at DiXiT Convention 1: Technology, Software, Standards
Net7
 
Trend Analysis sui Social Network - I risultati del progetto SenTaClAus
Net7
 
Word Embedding e word2vec: Introduzione ed Esperimenti Preliminari
Net7
 
Social Media Analysis... according to Net7
Net7
 
Io sono qui per voi - Giulio Andreini
Net7
 
C'è semantica in questo web
Net7
 
Rethinking the Role of SSH - Culture and Creativity
Net7
 
Pundit at 3rd DBpedia Community Meeting 2015
Net7
 
Lod portal and pundit @ Humanities Hack london2014
Net7
 
Looking at Words through Images - Presentation at CASVA, National Gallery of ...
Net7
 
Looking at Words through Images - Presentation at CASVA, National Gallery of ...
Net7
 

Recently uploaded (20)

PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
PDF
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
PDF
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
PPTX
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PPTX
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
PDF
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
CIFDAQ Market Wrap for the week of 4th July 2025
CIFDAQ
 
LOOPS in C Programming Language - Technology
RishabhDwivedi43
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
The 2025 InfraRed Report - Redpoint Ventures
Razin Mustafiz
 
UPDF - AI PDF Editor & Converter Key Features
DealFuel
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Kit-Works Team Study_20250627_한달만에만든사내서비스키링(양다윗).pdf
Wonjun Hwang
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
UiPath DevConnect 2025: Agentic Automation Community User Group Meeting
DianaGray10
 
Designing_the_Future_AI_Driven_Product_Experiences_Across_Devices.pptx
presentifyai
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
New ThousandEyes Product Innovations: Cisco Live June 2025
ThousandEyes
 
Agentic AI lifecycle for Enterprise Hyper-Automation
Debmalya Biswas
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 

Javascript, DOM, browsers and frameworks basics

  • 1. Javascript, DOM, browsers  and frameworks basics NetSeven HQ - 29 March 2011 Simone Fonda [email protected]
  • 2. Abstract Javascript basics (types, objects, .prototype, arguments, scope) Browsers (history, what they do) DOM (definition, example, history, scripting) Javascript Frameworks (examples) jQuery (chaining, .data(), events, onload/ready, bind vs live) Advanced topics (not covered)
  • 3. Javascript .. basics
  • 4. JAVASCRIPT - types . typeof "oh hai" // "another string", "", '' > "string" typeof 31512 // 1, 2, 3, .. 10.15, 3.1415, .. 134.1251 .. > "number" typeof true // false, 1 == 1, 1&&1, !1, !!!!!!0 > "boolean" function f() { alert('oh hai'); } typeof f > "function" typeof antani > "undefined"
  • 5. JAVASCRIPT - types .. typeof [] // [1, 2], ["oh", "hai"], [1, true, function() { alert('oh hai')}] > "object" var array = [true, false, 1, 3.14, 1/3, function() {alert('oh hai')}] for (i in array) { console.log(i, array[i], typeof(array[i])) } > 0 true boolean > 1 false boolean > 2 1 number > 3 3.14 number > 4 0.3333333333333333 number > 5 function () {alert('oh hai');} function
  • 6. JAVASCRIPT - types ... typeof {} // {a:1, b:2}, {a:"oh", b:"hai"}, {function() { alert('oh hai')} > "object" var ob = {a: true, b: false, c:1, d: 3.14, XYZ: 1/3, fufu: function() { alert('oh hai') }} for (i in ob) { console.log(i, ob[i], typeof(ob[i])) } > a true boolean > b false boolean > c 1 number > d 3.14 number > XYZ 0.3333333333333333 number > fufu function () { alert('oh hai'); } function
  • 7. JAVASCRIPT - types .... objects? var ob = {a: true, b: false, c:1, d: 3.14} ob.d // or use ob['d'] > 3.14 var ar = [1, 2, 3/2] ar.length // an array! >3 'oh hai'.length // a string ! >6 var fu = function() { alert('oh hai') } fu.toString() > "function() { alert('oh hai') }"
  • 8. JAVASCRIPT - object's .prototype String.prototype.evve = function() { return this.replace(/r/g, 'V') } "orrore un ramarro marrone".evve() > "oVVoVe un VamaVVo maVVone" - "Everything is an object" - "Objects can be extended" - "There's no such thing as Class"
  • 9. JAVASCRIPT - functions' arguments . Overload? function add(a, b, c, d) { return a+b+c+d; } function add(a, b, c) { return a+b+c; } function add(a, b) { return a+b; } add(1, 2) > .. == 3 ?? add(1, 2, 3) > .. == 6 ?? add(1, 2, 3, 4) > .. == 10 ??
  • 10. JAVASCRIPT - functions' arguments .. Overload? NO! Last definition prevails! function add(a, b, c, d) { return a+b+c+d; } function add(a, b, c) { return a+b+c; } function add(a, b) { return a+b; } add(1, 2) >3 add(1, 2, 3) // 3rd argument is just ignored .. >3 add(1, 2, 3, 4) // 3rd and 4th arguments are ignored >3
  • 11. JAVASCRIPT - functions' arguments ... Overload? Kind of, use arguments ! function add() { var r=0; for (i=0; i<arguments.length; i++) r += arguments[i]; return r; } add(1, 2, 3, 4, 5, 6, 7) > 28 add(1, 3/5, Math.PI, Math.pow(2, 1.55), Math.sqrt(2), -5) > 4.083977607854139
  • 12. JAVASCRIPT - functions' arguments .... Overload? Kind of, use arguments ! function add() { var r=0; for (i=0; i<arguments.length; i++) r += arguments[i]; return r; } add(1, 2, 3, 4, 'oh hai') > .. == ? add('oh hai', 2, 3, 4, 5) > .. == ?
  • 13. JAVASCRIPT - functions' arguments ..... Overload? Kind of, use arguments ! function add() { var r=0; for (i=0; i<arguments.length; i++) r += arguments[i]; return r; } add(1, 2, 3, 4, 'oh hai') // + used for string concatenation as soon > "10oh hai" // as a string is... added add('oh hai', 2, 3, 4, 5) // r is initially equal to 0 (the number) > "0oh hai2345"
  • 14. JAVASCRIPT - scope . Javascript (as a language) does NOT have a global scope.. .. it comes from the browser: window (and it's an object!!) <script> // outside everything (objects/functions) var foo = "oh hai"; </script> window.foo = "oh hai"; // directly attached to window object window['foo'] = "oh hai"; function doSomething() { // in a object/function without var foo = "oh hai"; }
  • 15. JAVASCRIPT - scope .. var foo = 'oh hai'; function doSomething() { var foo = 'Goodbye'; return foo; } console.log(foo, doSomething()) > .. == ?? var foo = 'oh hai'; function doSomething() { foo = 'Goodbye'; return foo; } console.log(foo, doSomething()) > .. == ??
  • 16. JAVASCRIPT - scope ... var foo = 'oh hai'; function doSomething() { var foo = 'Goodbye'; return foo; } console.log(foo, doSomething()) // global foo remains the same > oh hai Goodbye var foo = 'oh hai'; function doSomething() { foo = 'Goodbye'; return foo; } console.log(foo, doSomething()) // foo hasn't changed yet!! :P > oh hai Goodbye // next console.log() "Goodbye Goodbye"!
  • 17. Browsers retrieving, presenting, and traversing information resources on the World Wide Web, since 1980s.
  • 18. Browsers - a little bit of history . The history of the Web browser dates back in to the late 1980s, when a variety of technologies laid the foundation for the first Web browser, WorldWideWeb, by Tim Berners-Lee in 1991. That browser brought together a variety of existing and new software and hardware technologies. Ted Nelson and Douglas Engelbart developed the concept of hypertext long before Berners-Lee and CERN. It became the core of the World Wide Web. Berners-Lee does acknowledge Engelbart's contribution.
  • 19. Browsers - a little bit of history .. The introduction of the NCSA Mosaic Web browser in 1993 – one of the first graphical Web browsers – led to an explosion in Web use. Marc Andreessen, the leader of the Mosaic team at the National Center for Supercomputing Applications (NCSA), soon started his own company, named Netscape, and released the Mosaic- influenced Netscape Navigator in 1994, which quickly became the world's most popular browser, accounting for 90% of all Web use at its peak (see usage share of web browsers). Microsoft responded with its browser Internet Explorer in 1995 (also heavily influenced by Mosaic), initiating the industry's first browser war. By bundling Internet Explorer with Windows, Microsoft was able to leverage its dominance in the operating system market to take over the Web browser market; Internet Explorer usage share peaked at over 95% by 2002. The usage share of Internet Explorer has declined from over 62.1% in January 2010 to 56.0% in January 2011 according to Net Applications. In February 2011 its share has increased again to 56.8%.
  • 20. Browsers - a little bit of history ... Opera first appeared in 1996; although it has never achieved widespread use, it holds a stable share of in between 2.1% and 2.4%, and it has a substantial share of the fast-growingmobile phone Web browser market, being preinstalled on over 40 million phones. It is also available on several other embedded systems, including Nintendo's Wii video game console. In 1998, Netscape launched what was to become the Mozilla Foundation in an attempt to produce a competitive browser using the open source software model. That browser would eventually evolve into Firefox, which developed a respectable following while still in the beta stage of development; shortly after the release of Firefox 1.0 in late 2004, Firefox (all versions) accounted for 7.4% of browser use. The Firefox usage share has slowly declined in 2010, from 24.4% in January to 21.7% in February 2011. Apple's Safari had its first beta release in January 2003; it has a dominant share of Apple-based Web browsing, having risen from 4.5% usage share in January 2010 to 6.7% in February 2011. Its rendering engine, called WebKit, is also running in the standard browsers of several mobile phone platforms, including Apple iOS, Google Android, Nokia S60 and PalmwebOS. The most recent major entrant to the browser market is Google's WebKit-based Chrome, first released in September 2008. Its market share has quickly risen; its usage share has doubled from 5.2% in January 2010 to 10.9% in February 2011, but in recent months its growth is not as drastic as before.
  • 21. Browsers - a little bit of history .... The primary purpose of a web browser is to bring information resources to the user. This process begins when the user inputs a Uniform Resource Identifier (URI), for example http://en.wikipedia.org/, into the browser. The prefix of the URI determines how the URI will be interpreted. The most commonly used kind of URI starts with http: and identifies a resource to be retrieved over the Hypertext Transfer Protocol (HTTP). Many browsers also support a variety of other prefixes, such as https: for HTTPS, ftp: for the File Transfer Protocol, and file: for local files. Prefixes that the web browser cannot directly handle are often handed off to another application entirely. For example, mailto: URIs are usually passed to the user's default e-mail application and news: URIs are passed to the user's default newsgroup reader. In the case of http, https, file, and others, once the resource has been retrieved the web browser will display it. HTML is passed to the browser's layout engine to be transformed from markup to an interactive document. Aside from HTML, web browsers can generally display any kind of content that can be part of a web page. Most browsers can display images, audio, video, and XML files, and often have plug-ins to support Flash applications and Java applets. Upon encountering a file of an unsupported type or a file that is set up to be downloaded rather than displayed, the browser often prompts the user to save the file to disk or identify a program that can open it. Interactivity in a web page can also be supplied by JavaScript, which usually does not require a plugin. JavaScript can be used along with other technologies to allow "live" interaction with the web page's server via Ajax. In the most advanced browsers, JavaScript programs can produce interactive 2D graphics using the canvas API and fully rendered 3D graphics using WebGL. Information resources may contain hyperlinks to other information resources. Each link contains the URI of a resource to go to. When a link is clicked, the browser navigates to the resource indicated by the link's target URI, and the process of bringing content to the user begins again. Available web browsers range in features from minimal, text-based user interfaces with bare-bones support for HTML to rich user interfaces supporting a wide variety of file formats and protocols. Browsers which include additional components to support e-mail, Usenet news, and Internet Relay Chat (IRC), are sometimes referred to as "Internet suites" rather than merely "web browsers". All major web browsers allow the user to open multiple information resources at the same time, either in different browser windows or in different tabs of the same window. Major browsers also include pop-up blockers to prevent unwanted windows from "popping up" without the user's consent. Most web browsers can display a list of web pages that the user has bookmarked so that the user can quickly return to them. Bookmarks are also called "Favorites" in Internet Explorer. In addition, all major web browsers have some form of built-in web feed aggregator. In Mozilla Firefox, web feeds are formatted as "live bookmarks" and behave like a folder of bookmarks corresponding to recent entries in the feed. In Opera, a more traditional feed reader is included which stores and displays the contents of the feed. Furthermore, most browsers can be extended via plug-ins, downloadable components that provide additional features. Early web browsers supported only a very simple version of HTML. The rapid development of web browsers led to the development of non-standard dialects of HTML, leading to problems with interoperability. Modern web browsers support a combination of standards-based and de facto HTML and XHTML, which should be rendered in the same way by all browsers.
  • 22. Browsers - what they do for you - Downloads the requested page - Downloads included assets (css, javascript, images, ..) ... progressive content loading ... - Elements size - Float, positioning - User interaction (keyboard, mouse) - Handles events (keyboard, mouse, ajax, timers, ..) - Creates a DOM representation to interact with .......... ??
  • 24. DOM : Document Object Model . The Document Object Model (DOM) is an application programming interface (API) for valid HTML and well-formed XML documents. It defines the logical structure of documents and the way a document is accessed and manipulated
  • 25. DOM : Document Object Model .. <html> <head> <title>Oh hai</title> </head> <body> <span></span> <div>Immagine: <img src=''> </div> </body> <html>
  • 26. DOM : Document Object Model ... JavaScript was released by Netscape Communications in 1996 within Netscape Navigator 2.0. Netscape's competitor, Microsoft, released Internet Explorer 3.0 later the same year with a port of JavaScript called JScript. JavaScript and JScript let web developers create web pages with client-side interactivity. The limited facilities for detecting user-generated events and modifying the HTML document in the first generation of these languages eventually became known as "DOM Level 0" or "Legacy DOM". No independent standard was developed for DOM Level 0, but it was partly described in the specification of HTML4. For example, a form input element could be accessed as either "document.formName. inputName" or "document.forms[0].elements[0]". The Legacy DOM enabled client-side form validation and the popular "rollover" effect.
  • 27. DOM : Document Object Model .... In 1997, Netscape and Microsoft released version 4.0 of Netscape Navigator and Internet Explorer, adding support for Dynamic HTML (DHTML), functionality enabling changes to a loaded HTML document. The Intermediate DOMs enabled the manipulation of Cascading Style Sheet (CSS) properties which influence the display of a document. They also provided access to a new feature called "layers" via the "document.layers" property (Netscape Navigator) and the "document.all" property (Internet Explorer). Because of the fundamental incompatibilities in the Intermediate DOMs, cross-browser development required special handling for each supported browser.
  • 28. DOM : Document Object Model ..... The World Wide Web Consortium (W3C), founded in 1994 to promote open standards for the World Wide Web, brought Netscape Communications and Microsoft together with other companies to develop a standard for browser scripting languages, called "ECMAScript". After the release of ECMAScript, W3C began work on a standardized DOM. The initial DOM standard, known as "DOM Level 1", was recommended by W3C in late 1998. About the same time, Internet Explorer 5.0 shipped with limited support for DOM Level 1. DOM Level 1 provided a complete model for an entire HTML or XML document, including means to change any portion of the document. Non-conformant browsers such as Internet Explorer 4.x and Netscape 4.x were still widely used as late as 2000. DOM Level 2 was published in late 2000. It introduced the "getElementById" function as well as an event model and support for XML namespaces and CSS. DOM Level 3, the current release of the DOM specification, published in April 2004, added support for XPath and keyboard event handling, as well as an interface for serializing documents as XML. By 2005, large parts of W3C DOM were well-supported by common ECMAScript-enabled browsers, including Microsoft Internet Explorer version 6 (2001), Opera, Safari and Gecko-based browsers (like Mozilla, Firefox, SeaMonkey and Camino).
  • 29. DOM scripting . // Change the style of an H1 tag if (document.getElementsByTagName('h1').length > 0) { h = document.getElementsByTagName('h1')[0]; h.style.color = 'red'; h.style.fontFamily = 'Arial'; h.style.fontWeight = 'bold'; h.style.borderStyle = 'solid'; h.style.borderColor = '#c00'; h.style.borderWidth = '1px'; }
  • 30. DOM scripting .. window.onload = function() { // Call when document is loaded alert('oh hai'); } What if we need to call more than a single function?
  • 31. DOM scripting ... window.onload = function() { // Call when document is loaded alert('oh hai'); } function addLoadEvent(func) { // ADD a function to call when.. var oldonload = window.onload; if (typeof window.onload != 'function') { window.onload = func; } else { window.onload = function() { oldonload(); func(); } } } addLoadEvent(function() { alert('oh hai') });
  • 32. DOM scripting .... // call a function when user clicks on the first A inside a // certain container .. var container = document.getElementById('containerId'); if (!container) { return; } if (container.getElementsByTagName('a').length > 0) { var a = container.getElementsByTagName('a')[0]; a.onclick= function() { doSomething() } ; }
  • 33. DOM scripting ..... // Get x,y coordinates from a mouse click event function doSomething(e) { var posx = 0, posy = 0; if (!e) var e = window.event; // some passes e, some dont if (e.pageX || e.pageY) { posx = e.pageX; // safari and opera, NOT IE posy = e.pageY; } else if (e.clientX || e.clientY) { posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft; posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop; } // Use posx and posy .... }
  • 34. DOM scripting ...... function getData() { var xhr; try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); } // Internet Explorer catch (e) { try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } // Another IE catch (e2) { try { xhr = new XMLHttpRequest(); } // Firefox, Safari, .. catch (e3) { xhr = false; } } } xhr.onreadystatechange = function() { // Called quite often.. 1, 2, 3, 4 .. if (xhr.readyState == 4) { // 4 = transaction finished if (xhr.status == 200) document... = "Received:" + xhr.responseText; else document... = "Error code " + xhr.status; } }; xhr.open(GET, "data.txt", true); // Start the connection! xhr.send(null); }
  • 35. DOM scripting ....... document.createElement() event.target document.createTextNode() event.currentTarget document.createAttribute() event.bubbles .... .... node.nodeName stylesheet.href node.firstChild stylesheet.item node.previousSibling stylesheet.insertRule node.attributes stylesheet.deleteRule node.insertBefore() .... node.replaceChild() cssrule.cssText node.hasChildNodes() cssrule.parentRule node.replaceChild() cssrule.type node.hasAttributes() .... .... nodeIterator.nextNode() object.getAttribute() nodeInterator.previousNode() object.setAttribute() .... object.getElementsByTagName() range.setStart() .... range.setEnd() object.addEventListener() range.setStartBefore() object.dispatchEvent() range.setEndBefore() range.cloneContents()
  • 36. Javascript Frameworks TO THE RESCUE!
  • 37. Javascript frameworks to the rescue!  Cross browser DOM scripting made easy (selectors, events, ..) Ajax made easy (get, post, ..) More goodies (each(), map(), grep(), ...) Spice up your page with effects (slideUp(), hide(1000), ..) Large community (sharing problems and solutions) Tons of available scripts/plugins (too many??)
  • 38. Javascript frameworks to the rescue! . if (document.getElementsByTagName('h1').length > 0) { h = document.getElementsByTagName('h1')[0]; h.style.color = 'red'; h.style.borderStyle = 'solid'; h.style.borderColor = '#c00'; h.style.borderWidth = '1px'; } Using jQuery for Selectors: $('h1:first').css({color: 'red', border: '1px solid #c00'}) $('h1') ~= document.getElementsByTagName('h1') $('#foo') ~= document.getElementById('foo')
  • 39. Javascript frameworks to the rescue! .. window.onload = function() { // Call when document is loaded alert('oh hai'); } Using jQuery for events: $(document).ready(function() { alert('oh hai'); }); As many as you want, for free! (Not exactly the same behaviour.. more on this later.)
  • 40. Javascript frameworks to the rescue! ... // call a function when click on the first A inside a certain // container .. var container = document.getElementById('containerId'); if (!container) { return; } if (container.getElementsByTagName('a').length > 0) { var a = container.getElementsByTagName('a')[0]; a.onclick = function() { doSomething() } ; } Using jQuery for selectors and events: $('#containerId a:first').click(function() { doSomething() });
  • 41. Javascript frameworks to the rescue! .... function getData() { var xhr; try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); } // Internet Explorer catch (e) { try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); } // Another IE catch (e2) { try { xhr = new XMLHttpRequest(); } // Firefox, Safari, .. catch (e3) { xhr = false; } } } xhr.onreadystatechange = function() { // Called quite often.. 1, 2, 3, 4 .. if (xhr.readyState == 4) { // 4 = transaction finished if (xhr.status == 200) document... = "Received:" + xhr.responseText; else document... = "Error code " + xhr.status; } }; xhr.open(GET, "data.txt", true); // Start the connection! xhr.send(null); } Using jQuery for ajax: $.ajax({ url: "data.txt", success: function(data) { $('#foo').val(data); } });
  • 43. jQuery . Chaining: jQuery returns itself (sort of ......) $('#foo'); // == jQuery object $('#foo').css({border: '1px solid red'}); // == jQuery object $('#foo').click(function() { alert('Nice click') }); // == jQuery object $('#foo').hover(function() { alert('Over!') }); // == jQuery object ..... all of them are jQuery objects .....
  • 44. jQuery . Chaining: jQuery returns itself (sort of ......) $('#foo'); // == jQuery object $('#foo').css({border: '1px solid red'}); // == jQuery object $('#foo').click(function() { alert('Nice click') }); // == jQuery object $('#foo').hover(function() { alert('Over!') }); // == jQuery object ..... all of them are jQuery objects ..... $('#foo') .css({border: '1px solid red'}) .click(function() { alert('Nice click') }) .hover(function() { alert('Over!')}); // == jQuery object
  • 45. jQuery .. .data(): linking custom data to elements $('#foo').data('uri', 'http://my_precious_URI'); // storing $('#foo').data('type', 'IIP image'); // storing if ($('#foo').data('type') === 'IIP image')) // retrieving uri = $('#foo').data('uri'); $('#foo').removeData(); // deleting
  • 46. jQuery ... events: onload? document ready? Which order?? <html> <script src='http://code.jquery.com/jquery-1.5.js'></script> <script> $(document).ready(function() { console.log('document is ready'); }); window.onload = function() { console.log('window is loaded '); } console.log('This is executed'); </script> <body> </body> </html>
  • 47. jQuery ... events: onload? document ready? Which order?? $(document).ready(): called BEFORE window.onload !! DOM ready to be manipulated (hide, addclass, remove..) window.onload(): all the assets has been loaded (images, banners, ..) Answer: > This is executed > document is ready > window is loaded
  • 48. jQuery ... events: onload? document ready? Which order?? <html> <script src='http://code.jquery.com/jquery-1.5.js'></script> <script> $('#foo').html("Goodbye!"); </script> <body> <div id='foo'>Oh hai!</div> </body> </html> page == ??
  • 49. jQuery ... events: onload? document ready? Which order?? <html> <script src='http://code.jquery.com/jquery-1.5.js'></script> <script> $('#foo').html("Goodbye!"); </script> <body> <div id='foo'>Oh hai!</div> </body> </html> page == "Oh hai!": the div does not exist yet .... :(
  • 50. jQuery ... events: onload? document ready? Which order?? <html> <script src='http://code.jquery.com/jquery-1.5.js'></script> <script> $(document).ready(function() { $('#foo').html("Goodbye!"); }); </script> <body> <div id='foo'>Oh hai!</div> </body> </html> page == "Goodbye!"
  • 51. jQuery .... events: bind() versus live() $('.foo').click(function() { }) == $('foo').bind('click', function() { }) BUT $('foo').bind('click', function() { }) != $('foo').live('click', function() { });
  • 52. jQuery .... events: bind() versus live() <html> <script src='http://code.jquery.com/jquery-1.5.js'></script> <script> $('div.foo').click(function() { $('body').append("<div class='foo'>... Oh hai!!</div>") }); </script> <body><div class='foo'>Oh hai!</div></body> </html> What does this do? ..
  • 53. jQuery .... events: bind() versus live() <html> <script src='http://code.jquery.com/jquery-1.5.js'></script> <script> $('div.foo').click(function() { $('body').append("<div class='foo'>... Oh hai!!</div>") }); </script> <body><div class='foo'>Oh hai!</div></body> </html> What does this do? .. NOTHING! div doesnt exist yet!!! ;)
  • 54. jQuery .... events: bind() versus live() <html> <script src='http://code.jquery.com/jquery-1.5.js'></script> <script> $(document).ready(function() { $('div.foo').click(function() { $('body').append("<div class='foo'>... Oh hai!!</div>") }); }); </script> <body><div class='foo'>Oh hai!</div></body> </html> What does this do? ..
  • 55. jQuery .... events: bind() versus live() <html> <script src='http://code.jquery.com/jquery-1.5.js'></script> <script> $(document).ready(function() { $('div.foo').click(function() { $('body').append("<div class='foo'>... Oh hai!!</div>") }); }); </script> <body><div class='foo'>Oh hai!</div></body> </html> What does this do? .. adds a div.foo "... Oh hai!!" item by clicking on the first div, the one coming from the original document.
  • 56. jQuery .... events: bind() versus live() <html> <script src='http://code.jquery.com/jquery-1.5.js'></script> <script> $('div.foo').live('click', function() { $('body').append("<div class='foo'>... Oh hai!!</div>") }); </script> <body><div class='foo'>Oh hai!</div></body> </html> What does this do? ..
  • 57. jQuery .... events: bind() versus live() <html> <script src='http://code.jquery.com/jquery-1.5.js'></script> <script> $('div.foo').live('click', function() { $('body').append("<div class='foo'>... Oh hai!!</div>") }); </script> <body><div class='foo'>Oh hai!</div></body> </html> What does this do? .. adds a div.foo "... Oh hai!!" item by clicking on any div.foo item!! Even the future ones!
  • 58. Advanced topics .. are you curious? js closures ()() js meta-programming (code which modifies code) js timers js events, this object and scope js == vs === js eval js using callbacks (apply, call) js delayed script loading HTML/js optimization to get a snappier user experience (sprites, scripts optimizations, ..) jQuery vs other frameworks (prototype, mootools, ..) jQuery animations and chained animations jQuery ajax data retrieval (JSON?) jQuery plugins (how to build one)
  • 59. That's ALL! Download this presentaion in PDF from: http://bit.ly/ejLetd Simone Fonda [email protected]