Javascript, DOM, browsers and frameworks basics

59
Javascript, DOM, browsers and frameworks basics NetSeven HQ - 29 March 2011 Simone Fonda fonda@netseven.it

description

An introduction to Javascript, Browsers, the DOM and JS Frameworks

Transcript of Javascript, DOM, browsers and frameworks basics

Page 1: Javascript, DOM, browsers and frameworks basics

Javascript, DOM, browsers and frameworks basics

NetSeven HQ - 29 March 2011

Simone Fonda [email protected]

Page 2: Javascript, DOM, browsers and frameworks basics

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)

Page 3: Javascript, DOM, browsers and frameworks basics

Javascript

.. basics

Page 4: Javascript, DOM, browsers and frameworks 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"

Page 5: Javascript, DOM, browsers and frameworks basics

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

Page 6: Javascript, DOM, browsers and frameworks basics

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

Page 7: Javascript, DOM, browsers and frameworks basics

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') }"

Page 8: Javascript, DOM, browsers and frameworks basics

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"

Page 9: Javascript, DOM, browsers and frameworks basics

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 ??

Page 10: Javascript, DOM, browsers and frameworks basics

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

Page 11: Javascript, DOM, browsers and frameworks basics

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

Page 12: Javascript, DOM, browsers and frameworks basics

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)> .. == ?

Page 13: Javascript, DOM, browsers and frameworks basics

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... addedadd('oh hai', 2, 3, 4, 5) // r is initially equal to 0 (the number)> "0oh hai2345"

Page 14: Javascript, DOM, browsers and frameworks basics

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 objectwindow['foo'] = "oh hai";

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

Page 15: Javascript, DOM, browsers and frameworks basics

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())> .. == ??

Page 16: Javascript, DOM, browsers and frameworks basics

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"!

Page 17: Javascript, DOM, browsers and frameworks basics

Browsers

retrieving, presenting, and traversing information resources on the World Wide Web, since 1980s.

Page 18: Javascript, DOM, browsers and frameworks basics

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.

Page 19: Javascript, DOM, browsers and frameworks basics

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%.

Page 20: Javascript, DOM, browsers and frameworks basics

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.

Page 21: Javascript, DOM, browsers and frameworks basics

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.

Page 22: Javascript, DOM, browsers and frameworks basics

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 .......... ??

Page 23: Javascript, DOM, browsers and frameworks basics

DOM

the Document Object Model

Page 24: Javascript, DOM, browsers and frameworks basics

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

Page 25: Javascript, DOM, browsers and frameworks basics

DOM : Document Object Model ..

<html> <head> <title>Oh hai</title> </head> <body> <span></span> <div>Immagine: <img src=''> </div> </body><html>

Page 26: Javascript, DOM, browsers and frameworks basics

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.

Page 27: Javascript, DOM, browsers and frameworks basics

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.

Page 28: Javascript, DOM, browsers and frameworks basics

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).

Page 29: Javascript, DOM, browsers and frameworks basics

DOM scripting .

// Change the style of an H1 tagif (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';}

Page 30: Javascript, DOM, browsers and frameworks basics

DOM scripting ..

window.onload = function() { // Call when document is loaded alert('oh hai');}

What if we need to call more than a single function?

Page 31: Javascript, DOM, browsers and frameworks basics

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') });

Page 32: Javascript, DOM, browsers and frameworks basics

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() } ; }

Page 33: Javascript, DOM, browsers and frameworks basics

DOM scripting .....

// Get x,y coordinates from a mouse click eventfunction 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 ....}

Page 34: Javascript, DOM, browsers and frameworks basics

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); }

Page 35: Javascript, DOM, browsers and frameworks basics

DOM scripting .......document.createElement()document.createTextNode()document.createAttribute()....node.nodeNamenode.firstChildnode.previousSiblingnode.attributesnode.insertBefore()node.replaceChild()node.hasChildNodes()node.replaceChild()node.hasAttributes()....object.getAttribute()object.setAttribute()object.getElementsByTagName()....object.addEventListener()object.dispatchEvent()

event.targetevent.currentTargetevent.bubbles....stylesheet.hrefstylesheet.itemstylesheet.insertRulestylesheet.deleteRule....cssrule.cssTextcssrule.parentRulecssrule.type....nodeIterator.nextNode()nodeInterator.previousNode()....range.setStart()range.setEnd()range.setStartBefore()range.setEndBefore()range.cloneContents()

Page 36: Javascript, DOM, browsers and frameworks basics

Javascript Frameworks

TO THE RESCUE!

Page 37: Javascript, DOM, browsers and frameworks basics

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??)

Page 38: Javascript, DOM, browsers and frameworks basics

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')

Page 39: Javascript, DOM, browsers and frameworks basics

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.)

Page 40: Javascript, DOM, browsers and frameworks basics

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() });

Page 41: Javascript, DOM, browsers and frameworks basics

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); }});

Page 42: Javascript, DOM, browsers and frameworks basics

jQuery

random tips and tricks

Page 43: Javascript, DOM, browsers and frameworks basics

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 .....

Page 44: Javascript, DOM, browsers and frameworks basics

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

Page 45: Javascript, DOM, browsers and frameworks basics

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

Page 46: Javascript, DOM, browsers and frameworks basics

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>

Page 47: Javascript, DOM, browsers and frameworks basics

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

Page 48: Javascript, DOM, browsers and frameworks basics

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 == ??

Page 49: Javascript, DOM, browsers and frameworks basics

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 .... :(

Page 50: Javascript, DOM, browsers and frameworks basics

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!"

Page 51: Javascript, DOM, browsers and frameworks basics

jQuery ....

events: bind() versus live()

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

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

BUT

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

$('foo').live('click', function() { });

Page 52: Javascript, DOM, browsers and frameworks basics

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? ..

Page 53: Javascript, DOM, browsers and frameworks basics

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!!! ;)

Page 54: Javascript, DOM, browsers and frameworks basics

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? ..

Page 55: Javascript, DOM, browsers and frameworks basics

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.

Page 56: Javascript, DOM, browsers and frameworks basics

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? ..

Page 57: Javascript, DOM, browsers and frameworks basics

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!

Page 58: Javascript, DOM, browsers and frameworks basics

Advanced topics .. are you curious?

js closures ()()js meta-programming (code which modifies code)js timersjs events, this object and scopejs == vs ===js evaljs 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 animationsjQuery ajax data retrieval (JSON?)jQuery plugins (how to build one)

Page 59: Javascript, DOM, browsers and frameworks basics

That's ALL!

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

Simone Fonda [email protected]