SlideShare une entreprise Scribd logo
1  sur  59
Télécharger pour lire hors ligne
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

Contenu connexe

Tendances

Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
baygross
 

Tendances (20)

Javascript inside Browser (DOM)
Javascript inside Browser (DOM)Javascript inside Browser (DOM)
Javascript inside Browser (DOM)
 
Web Development Introduction to jQuery
Web Development Introduction to jQueryWeb Development Introduction to jQuery
Web Development Introduction to jQuery
 
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...
Internet and Web Technology (CLASS-8) [jQuery and JSON] | NIC/NIELIT Web Tech...
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
 
Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2Javascript: Ajax & DOM Manipulation v1.2
Javascript: Ajax & DOM Manipulation v1.2
 
Internet and Web Technology (CLASS-6) [BOM]
Internet and Web Technology (CLASS-6) [BOM] Internet and Web Technology (CLASS-6) [BOM]
Internet and Web Technology (CLASS-6) [BOM]
 
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web TechnologyInternet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-9) [React.js] | NIC/NIELIT Web Technology
 
jQuery
jQueryjQuery
jQuery
 
KMUTNB - Internet Programming 4/7
KMUTNB - Internet Programming 4/7KMUTNB - Internet Programming 4/7
KMUTNB - Internet Programming 4/7
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Part 7
Part 7Part 7
Part 7
 
AJAX Workshop Notes
AJAX Workshop NotesAJAX Workshop Notes
AJAX Workshop Notes
 
Unit 4(it workshop)
Unit 4(it workshop)Unit 4(it workshop)
Unit 4(it workshop)
 
Xml part 6
Xml part 6Xml part 6
Xml part 6
 
JavaScript and jQuery Basics
JavaScript and jQuery BasicsJavaScript and jQuery Basics
JavaScript and jQuery Basics
 
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
 
jQuery Best Practice
jQuery Best Practice jQuery Best Practice
jQuery Best Practice
 
jQuery Introduction
jQuery IntroductionjQuery Introduction
jQuery Introduction
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
J Query Public
J Query PublicJ Query Public
J Query Public
 

En vedette

DOM ( Document Object Model )
DOM ( Document Object Model )DOM ( Document Object Model )
DOM ( Document Object Model )
ITSTB
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
chomas kandar
 
JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)
Nicholas Zakas
 

En vedette (18)

Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
 
學習JavaScript_Dom
學習JavaScript_Dom學習JavaScript_Dom
學習JavaScript_Dom
 
javascript objects
javascript objectsjavascript objects
javascript objects
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
JavaScript regular expression
JavaScript regular expressionJavaScript regular expression
JavaScript regular expression
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
Javascript validating form
Javascript validating formJavascript validating form
Javascript validating form
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScript
 
Document object model(dom)
Document object model(dom)Document object model(dom)
Document object model(dom)
 
DOM ( Document Object Model )
DOM ( Document Object Model )DOM ( Document Object Model )
DOM ( Document Object Model )
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
 
Javascript
JavascriptJavascript
Javascript
 
Regular Expressions
Regular ExpressionsRegular Expressions
Regular Expressions
 
Introduction to Regular Expressions
Introduction to Regular ExpressionsIntroduction to Regular Expressions
Introduction to Regular Expressions
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)JavaScript APIs you’ve never heard of (and some you have)
JavaScript APIs you’ve never heard of (and some you have)
 
Maintainable JavaScript 2012
Maintainable JavaScript 2012Maintainable JavaScript 2012
Maintainable JavaScript 2012
 

Similaire à Javascript, DOM, browsers and frameworks basics

Speak the Web 15.02.2010
Speak the Web 15.02.2010Speak the Web 15.02.2010
Speak the Web 15.02.2010
Patrick Lauke
 
Ajax with DWR
Ajax with DWRAjax with DWR
Ajax with DWR
gouthamrv
 
Fixing the mobile web - Internet World Romania
Fixing the mobile web - Internet World RomaniaFixing the mobile web - Internet World Romania
Fixing the mobile web - Internet World Romania
Christian Heilmann
 
HTML5 Who what where when why how
HTML5 Who what where when why howHTML5 Who what where when why how
HTML5 Who what where when why how
brucelawson
 

Similaire à Javascript, DOM, browsers and frameworks basics (20)

Yahoo is open to developers
Yahoo is open to developersYahoo is open to developers
Yahoo is open to developers
 
HTML5: An Introduction To Next Generation Web Development
HTML5: An Introduction To Next Generation Web DevelopmentHTML5: An Introduction To Next Generation Web Development
HTML5: An Introduction To Next Generation Web Development
 
Speak the Web 15.02.2010
Speak the Web 15.02.2010Speak the Web 15.02.2010
Speak the Web 15.02.2010
 
Exploring the Internet of Things Using Ruby
Exploring the Internet of Things Using RubyExploring the Internet of Things Using Ruby
Exploring the Internet of Things Using Ruby
 
Get Ahead with HTML5 on Moible
Get Ahead with HTML5 on MoibleGet Ahead with HTML5 on Moible
Get Ahead with HTML5 on Moible
 
4Developers 2015: People don't give a f**k of JavaScript - Aurelio De Rosa
4Developers 2015: People don't give a f**k of JavaScript - Aurelio De Rosa4Developers 2015: People don't give a f**k of JavaScript - Aurelio De Rosa
4Developers 2015: People don't give a f**k of JavaScript - Aurelio De Rosa
 
HTML5: An Introduction To Next Generation Web Development
HTML5: An Introduction To Next Generation Web DevelopmentHTML5: An Introduction To Next Generation Web Development
HTML5: An Introduction To Next Generation Web Development
 
Echo HTML5
Echo HTML5Echo HTML5
Echo HTML5
 
Advanced Web Development
Advanced Web DevelopmentAdvanced Web Development
Advanced Web Development
 
Web browser
Web browserWeb browser
Web browser
 
Students of Navgujarat College of Computer Applications, Ahmedabad felt excit...
Students of Navgujarat College of Computer Applications, Ahmedabad felt excit...Students of Navgujarat College of Computer Applications, Ahmedabad felt excit...
Students of Navgujarat College of Computer Applications, Ahmedabad felt excit...
 
Ajax with DWR
Ajax with DWRAjax with DWR
Ajax with DWR
 
Fixing the mobile web - Internet World Romania
Fixing the mobile web - Internet World RomaniaFixing the mobile web - Internet World Romania
Fixing the mobile web - Internet World Romania
 
Watir Presentation Sumanth Krishna. A
Watir Presentation   Sumanth Krishna. AWatir Presentation   Sumanth Krishna. A
Watir Presentation Sumanth Krishna. A
 
OBJECT ORIENTED ROGRAMMING With Question And Answer Full
OBJECT ORIENTED ROGRAMMING With Question And Answer  FullOBJECT ORIENTED ROGRAMMING With Question And Answer  Full
OBJECT ORIENTED ROGRAMMING With Question And Answer Full
 
Html 5 in a big nutshell
Html 5 in a big nutshellHtml 5 in a big nutshell
Html 5 in a big nutshell
 
Adding Meaning To Your Data
Adding Meaning To Your DataAdding Meaning To Your Data
Adding Meaning To Your Data
 
Mashups MAX 360|MAX 2008 Unconference
Mashups MAX 360|MAX 2008 UnconferenceMashups MAX 360|MAX 2008 Unconference
Mashups MAX 360|MAX 2008 Unconference
 
Html5
Html5Html5
Html5
 
HTML5 Who what where when why how
HTML5 Who what where when why howHTML5 Who what where when why how
HTML5 Who what where when why how
 

Plus de Net7

Looking at Words through Images - Presentation at CASVA, National Gallery of ...
Looking at Words through Images - Presentation at CASVA, National Gallery of ...Looking at Words through Images - Presentation at CASVA, National Gallery of ...
Looking at Words through Images - Presentation at CASVA, National Gallery of ...
Net7
 

Plus de Net7 (20)

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

Dernier

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Dernier (20)

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 

Javascript, DOM, browsers and frameworks basics

  • 1. Javascript, DOM, browsers  and frameworks basics NetSeven HQ - 29 March 2011 Simone Fonda fonda@netseven.it
  • 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 fonda@netseven.it