SlideShare a Scribd company logo
Javascript & jQuery 
A pragmatic introduction 
November 2014 
Ibán Martínez 
iban@nnset.com 
www.openshopen.com
Javascript
Data types : Number 
NO integers, just doubles 
(double­precision 
64­bit 
format IEEE 754 values) 
Not called doubles, called number.
Data types : Number 
typeof(37); 
=> 'number' 
typeof(3.14); 
=> 'number' 
typeof(Infinity); 
=> 'number'
Data types : Number 
typeof(37); 
=> 'number' 
typeof(3.14); 
=> 'number' 
typeof(Infinity); 
=> 'number' 
Maths disagrees with 
Javascript : 
[...] 
In mathematics, "infinity" is 
often incorrectly treated as 
if it were a number. 
In this context infinity is 
not itself a quantity but 
rather a direction or open 
possibility 
[…] 
http://en.wikipedia.org/wiki/Infinity
Data types : Number 
0.1 + 0.2 == 0.3; 
=> false
Data types : Number 
0.1 + 0.2 == 0.3; 
=> false 
0.1 + 0.2; 
=> 0.30000000000000004
Data types : Number 
0.1 + 0.2 == 0.3; 
=> false 
0.1 + 0.2; 
=> 0.30000000000000004 
You may 'fix' that issue like this : 
(0.1 + 0.2).toFixed(2) == 0.3; 
=> true
Data types : Number 
parseInt(3.99); 
=> 3 
parseInt('123', 10); 
=> 123 
parseInt('11', 2); 
=> 3 
Math.floor(3.99); 
=> 3 
Math.floor(3.01); 
=> 3 
Math.ceil(3.99); 
=> 4 
Math.ceil(3.01); 
=> 4 
Base to use
Data types : Number 
NaN (Not a Number) 
ParseInt('hello', 10); 
=> NaN
Data types : Number 
NaN (Not a Number) 
ParseInt('hello', 10); 
=> NaN 
NaN + 5; 
=> NaN 
isNaN(NaN); 
=> true
Data types : Number 
NaN (Not a Number) 
ParseInt('hello', 10); 
=> NaN 
NaN + 5; 
=> NaN 
isNaN(NaN); 
=> true 
typeof(NaN); 
?
Data types : Number 
NaN (Not a Number) 
ParseInt('hello', 10); 
=> NaN 
NaN + 5; 
=> NaN 
isNaN(NaN); 
=> true 
typeof(NaN); 
? 
typeof (NaN); 
=> 'number'
Data types : Number 
NaN (Not a Number) 
ParseInt('hello', 10) 
=> NaN 
NaN + 5 
NaN 
NaN => == NaN 
isNaN(=> false 
NaN) 
=> true 
typeof (NaN) 
? 
typeof (NaN) 
=> 'number'
Data types : String 
They're sequences of Unicode 
characters with each character 
represented by a 16­bit 
number.
Data types : String 
'hello'.length; 
=> 5 
'hello'.charAt(0); 
=> 'h' 
'hello, world'.replace('hello', 'goodbye'); 
=> 'goodbye, world' 
'hello'.toUpperCase(); 
=> 'HELLO'
Data types : String 
'1' == 1; 
'1' == parseInt(1); 
=> true 
'1' == 2; 
=> false 
'1' === 1; 
=> false
Data types : String 
'1' == 1; 
'1' == parseInt(1); 
=> true 
String; 
'instanceof 1' == 2; 
=> false 
string' false 
'1' === 1; 
'my => => false
Data types : Boolean 
false, 0, the empty string (""), 
NaN, null, and undefined all become 
false. 
All other values become 
true.
Data types : null & undefined 
undefined : declared but not 
initializated, not an actual value. 
null : is a value.
Data types : null & undefined 
undefined : declared but not 
initializated. 
null : is a value. 
Be aware of : 
( undefined == null ) => true 
( null == undefined ) => true
Data types : Arrays 
List of items. 
var a = new Array(); 
var a = ['dog', 'cat', 'hen']; 
typeof a[90]; 
=> undefined 
a.push('fish'); 
a.length; 
=> 4
Data types : Arrays 
List of items. 
.length isn't necessarily the number of items in 
the array. 
var a = ['dog', 'cat', 'hen']; 
a[100] = 'fox'; 
a.length; 
=> 101 
Remember — the length of the array is one more than 
the highest index.
jQuery 
http://jquery.com/
jQuery objects 
$.fn namespace 
Methods called on jQuery 
selections are in the 
$.fn namespace 
typeof $('h1'); 
=> 'object' 
$ namespace 
Methods in the $ 
namespace are generally 
utility­type 
methods, 
and do not work with 
selections. 
$.each([ 52, 97 ], function( index, value ) { 
alert( index + ": " + value ); 
}); 
http://learn.jquery.com/using­jquery­core/ 
dollar­object­vs­function/
jQuery selectors 
Class Selector $('.class') http://api.jquery.com/class­selector/ 
<div class="myClass">Hello</div> 
<p class="myClass">World</p> 
<script> 
$( '.myClass' ).each( function() { 
$( this ).text( 'Selected' ); 
}); 
</script> 
ID Selector $('#id') http://api.jquery.com/id­selector/ 
<div id="myId">Hello</div> 
<script> 
$( '#myId' ).each( function() { 
$( this ).text( 'Selected' ); 
}); 
</script> 
$( this ) is the 
jQuery object that 
manipulates current 
DOM item, in this 
example will be : 
<div class="myClass"> 
at first iteration and 
<p class="myClass"> 
at second iteration.
jQuery selectors 
Has Attribute Selector [name] http://api.jquery.com/has­attribute­selector/ 
<div id="myId">Hello</div> 
<div id="herId">Hello 2</div> 
<div>No ID</div> 
<script> 
$( 'div[id]' ).each( function() { 
$( this ).text( 'Selected' ); 
}); 
</script> 
Attribute Equals Selector [name="value"] 
http://api.jquery.com/attribute­equals­selector/ 
<div> 
<input type="radio" name="newsletter" value="Cold Fusion"> 
<input type="radio" name="newsletter" value="Evil Plans"> 
</div> 
<script> 
$( 'input[value=”Evil Plans”]' ).remove(); 
</script>
jQuery CSS manipulation 
$('').css (getter) http://api.jquery.com/css/ 
<div style="background­color: 
blue;">Hello</div> 
<script> 
$( 'div[style]' ).each( function() { 
alert( $(this).css('background­color') 
); 
}); 
</script> 
$('').css (setter) 
<div style="background­color: 
blue;">Hello</div> 
<script> 
$( 'div[style]' ).on( 'mouseover', function() { 
$(this).css('background­color', 
red ); 
}); 
</script>
jQuery CSS manipulation 
$('').hasClass http://api.jquery.com/hasClass/ 
<div class='myClass'>Hello</div> 
<script> 
$( 'div' ).each( function() { 
if( $(this).hasClass('myClass') == true ){ … } 
}); 
</script> 
$('').addClass http://api.jquery.com/addClass/ 
$('').removeClass http://api.jquery.com/removeClass/ 
<div style="background­color: 
blue;">Hello</div> 
<script> 
$( 'div[style]' ).on( 'mouseover', function() { 
if( !$(this).hasClass('myClass') ){ 
$(this).addClass('myClass'); 
} 
}); 
</script>
jQuery Events 
$( document ).ready() 
The ready event occurs after the HTML document has been loaded. 
<script> 
$( document ).ready( function() { 
console.log( 'HTML is ready!' ); 
}); 
</script> 
$( window ).load() 
The load event will run once the entire page (images or iframes), 
not just the DOM, is ready. 
<script> 
$( window ).load( function() { 
console.log( 'All assets and HTML are ready!' ); 
}); 
</script> 
http://learn.jquery.com/using­jquery­core/ 
document­ready/ 
http://stackoverflow.com/questions/3698200/window­onload­vs­document­ready
jQuery Events 
Main points for $( document ).ready(): 
http://stackoverflow.com/a/18339794 
● It will not wait for the images to get loaded. 
● Used to execute JavaScript when the DOM is 
completely loaded. 
● Put event handlers here. 
● Can be used multiple times. 
● Replace $ with jQuery when you receive “$ is not 
defined.” 
● Not used if you want to manipulate images Use $ 
(window).load() instead.
jQuery Events : Trigger & On 
Fire a custom event using $.fn → trigger() method. 
<script> 
$( 'div' ).on( 'mouseover', function() { 
if( $(this).hasClass('isWinner') ){ 
$(this).trigger('userHasWon'); 
} 
}); 
</script> 
Capture a custom event using $.fn → on() method. 
<script> 
$( 'div' ).on( 'userHasWon', function( event ) { 
event.preventDefault(); 
sendNotificationToServer(); 
updateTopNavBarWithReward(); 
}); 
</script> 
http://api.jquery.com/trigger/
JQuery : AJAX/AJAJ 
http://api.jquery.com/jquery.ajax/ 
Asynchronous JavaScript And XML 
Asynchronous JavaScript And JSON 
jQuery allows you to perform synchronous requests. 
synchronous JavaScript And XML 
synchronous JavaScript And JSON
JQuery : AJAX/AJAJ 
What is AJAX? 
Web server 
Get/Post request 
XML/JSON response 
Javascript code asks for some data 
and updates some DOM elements, page is 
not fully reloaded just partially 
updated.
JQuery : AJAX/AJAJ 
Asynchronous mode 
Method calls results can not be collected 
on natural code sequence order, they may 
arrive later (asynchronously). 
So you have to be prepared to process 
Ajax calls results anytime.
JQuery : AJAX/AJAJ 
Asynchronous mode 
<form action='http://www.mySite.com/action.php' method='POST'></form> 
$( 'form' ).on( 'submit', function( event ) { 
// Do not perform form action until Ajax response is received. 
event.preventDefault(); 
var shopName = $('form input[name="shopName"]').val(); 
checkShopName( shopName ); 
// Do not perform form action until Ajax response is received. 
return false; 
}); 
function checkShopName( name ) 
{ 
showSpinner(); 
performShopNameCheck( name ); 
}
JQuery : AJAX/AJAJ 
Asynchronous mode 
function performShopNameCheck( shopName ) 
{ 
$.ajax({ 
url : $('form').attr('action'), 
type: $('form').attr('method'), 
data: { shop: shopName, domain:'openshopen.com' }, 
success: function( response ) 
{ 
var valid = isResponseValid( response ); 
if( valid ){ 
// As code sequence was broken before, we may use events 
// to process results. 
$('form').trigger('redirectToSuccessPage'); 
} 
else{ 
$('form').trigger('reloadPageWithErrors', response.errors ); 
} 
}, 
error: function( jqXHR , textStatus , errorThrown ){ 
$('form').trigger('redirectToErrorPage'); 
} 
}); 
}
JQuery : AJAX/AJAJ 
Synchronous mode 
All code runs in sequence, methods will 
return values and block sequence until 
they finish their job.
JQuery : AJAX/AJAJ 
Synchronous mode 
$( 'form' ).on( 'submit', function( event ) { 
event.preventDefault(); 
var shopName = $('form input[name="shopName"]').val(); 
if( checkShopName( shopName ) ){ 
redirectToSuccessPage(); 
} 
else{ 
reloadPageWithErrors(); 
} 
}); 
function checkShopName( name ) 
{ 
showSpinner(); 
return performShopNameCheck( name ); 
} 
Sequence will end up waiting for 
an AJAX call, some browsers while 
they are synchronously waiting, do 
not show DOM changes, so spinner 
may not be shown to users.
JQuery : AJAX/AJAJ 
Synchronous mode 
function performShopNameCheck( shopName ) 
{ 
$.ajax({ 
url : $('form').attr('action'), 
type: $('form').attr('method'), 
data: { shop: shopName, domain:'openshopen.com' }, 
async : false, 
success: function( response ) 
{ 
return isResponseValid( response ); 
}, 
error: function( jqXHR , textStatus , errorThrown ){ 
return false; 
} 
}); 
}
JQuery : AJAX/AJAJ 
Shorthands : POST 
$.ajax({ 
type: 'POST', 
url: 'example.php', 
data: formData, 
success: function() { 
alert( 'success' ); 
}, 
done: function() { 
alert( 'second success' ); 
}, 
fail: function() { 
alert( 'error' ); 
}, 
always: function() { 
alert( 'finished' ); 
}, 
}); 
$.post( 'example.php', formData, function({ 
alert( 'success' ); 
}) 
.done(function() { 
alert( 'second success' ); 
}) 
.fail(function() { 
alert( 'error' ); 
}) 
.always(function() { 
alert( 'finished' ); 
}); 
These are equivalent. 
http://api.jquery.com/jquery.post/
$.ajax({ 
JQuery : AJAX/AJAJ 
type: 'GET', 
url: 'example.php', 
data: formData, 
success: function() { 
alert( 'success' ); 
}, 
done: function() { 
Shorthands : GET 
alert( 'second success' ); 
}, 
fail: function() { 
alert( 'error' ); 
}, 
always: function() { 
alert( 'finished' ); 
}, 
}); 
$.get( 'example.php', formData, function({ 
alert( 'success' ); 
}) 
.done(function() { 
alert( 'second success' ); 
}) 
.fail(function() { 
alert( 'error' ); 
}) 
.always(function() { 
alert( 'finished' ); 
}); 
http://api.jquery.com/jquery.get/ 
These are equivalent.
Javascript & jQuery 
A pragmatic introduction 
November 2014 
Ibán Martínez 
iban@nnset.com 
https://developer.mozilla.org/en­US/ 
docs/Web/JavaScript/A_re­introduction_ 
to_JavaScript 
http://blog.mgechev.com/2013/02/22/javascript­the­weird­parts/ 
https://medium.com/@daffl/javascript­the­weird­parts­8ff3da55798e 
www.openshopen.com 
http://learn.jquery.com/

More Related Content

What's hot

Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
Daniel Knell
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
Guilherme Blanco
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
Rafael Dohms
 
Introduction to CQRS and Event Sourcing
Introduction to CQRS and Event SourcingIntroduction to CQRS and Event Sourcing
Introduction to CQRS and Event Sourcing
Samuel ROZE
 
Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»e-Legion
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
sergioafp
 
Instant Dynamic Forms with #states
Instant Dynamic Forms with #statesInstant Dynamic Forms with #states
Instant Dynamic Forms with #statesKonstantin Käfer
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
Azim Kurt
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
Rafael Dohms
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
Leonardo Proietti
 
Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012
Rafael Dohms
 
Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Proposed PHP function: is_literal()
Proposed PHP function: is_literal()
Craig Francis
 
HirshHorn theme: how I created it
HirshHorn theme: how I created itHirshHorn theme: how I created it
HirshHorn theme: how I created it
Paul Bearne
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
Mohamed Mosaad
 
Codeware
CodewareCodeware
Codeware
Uri Nativ
 
Dollar symbol
Dollar symbolDollar symbol
Dollar symbol
Aaron Huang
 
PhoneGap: Local Storage
PhoneGap: Local StoragePhoneGap: Local Storage
PhoneGap: Local Storage
Ivano Malavolta
 
Drupal csu-open atriumname
Drupal csu-open atriumnameDrupal csu-open atriumname
Drupal csu-open atriumname
Emanuele Quinto
 

What's hot (20)

jQuery introduction
jQuery introductionjQuery introduction
jQuery introduction
 
Symfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technologySymfony2 Building on Alpha / Beta technology
Symfony2 Building on Alpha / Beta technology
 
Object Calisthenics Applied to PHP
Object Calisthenics Applied to PHPObject Calisthenics Applied to PHP
Object Calisthenics Applied to PHP
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
 
Introduction to CQRS and Event Sourcing
Introduction to CQRS and Event SourcingIntroduction to CQRS and Event Sourcing
Introduction to CQRS and Event Sourcing
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 
Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»
 
Advanced jQuery
Advanced jQueryAdvanced jQuery
Advanced jQuery
 
Instant Dynamic Forms with #states
Instant Dynamic Forms with #statesInstant Dynamic Forms with #states
Instant Dynamic Forms with #states
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Your code sucks, let's fix it
Your code sucks, let's fix itYour code sucks, let's fix it
Your code sucks, let's fix it
 
Symfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il clienteSymfony2, creare bundle e valore per il cliente
Symfony2, creare bundle e valore per il cliente
 
Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012Your code sucks, let's fix it - PHP Master Series 2012
Your code sucks, let's fix it - PHP Master Series 2012
 
Proposed PHP function: is_literal()
Proposed PHP function: is_literal()Proposed PHP function: is_literal()
Proposed PHP function: is_literal()
 
HirshHorn theme: how I created it
HirshHorn theme: how I created itHirshHorn theme: how I created it
HirshHorn theme: how I created it
 
Dig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup CairoDig Deeper into WordPress - WD Meetup Cairo
Dig Deeper into WordPress - WD Meetup Cairo
 
Codeware
CodewareCodeware
Codeware
 
Dollar symbol
Dollar symbolDollar symbol
Dollar symbol
 
PhoneGap: Local Storage
PhoneGap: Local StoragePhoneGap: Local Storage
PhoneGap: Local Storage
 
Drupal csu-open atriumname
Drupal csu-open atriumnameDrupal csu-open atriumname
Drupal csu-open atriumname
 

Viewers also liked

Getting started with jQuery
Getting started with jQueryGetting started with jQuery
Getting started with jQuery
Gill Cleeren
 
XSS Remediation
XSS RemediationXSS Remediation
XSS Remediation
Denim Group
 
6 Months with WebRTC
6 Months with WebRTC6 Months with WebRTC
6 Months with WebRTC
Arin Sime
 
Exploring the Possibilities of Sencha and WebRTC
Exploring the Possibilities of Sencha and WebRTCExploring the Possibilities of Sencha and WebRTC
Exploring the Possibilities of Sencha and WebRTC
Grgur Grisogono
 
Translation Studies
Translation StudiesTranslation Studies
Translation Studies
Ardiansyah -
 
Tripadvisor- PPT
Tripadvisor- PPTTripadvisor- PPT
Tripadvisor- PPTElisabeth
 
MLA Style Guide
MLA Style GuideMLA Style Guide
MLA Style Guideclover66
 
Retirement Income by KJH Financial Services
Retirement Income by KJH Financial ServicesRetirement Income by KJH Financial Services
Retirement Income by KJH Financial Services
Kimberly Howard, CFP
 
How to design for the web
How to design for the webHow to design for the web
How to design for the web
Cyber-Duck
 
Agility at Vietnamworks
Agility at VietnamworksAgility at Vietnamworks
Agility at Vietnamworks
Chris Shayan
 
Project management at a UX focused digital agency
Project management at a UX focused digital agencyProject management at a UX focused digital agency
Project management at a UX focused digital agency
Cyber-Duck
 
#UBA_#Ciberseguridad_#Cibercrimen_#Privacidad
#UBA_#Ciberseguridad_#Cibercrimen_#Privacidad#UBA_#Ciberseguridad_#Cibercrimen_#Privacidad
#UBA_#Ciberseguridad_#Cibercrimen_#Privacidad
Mariano M. del Río
 
Storie dal futuro: persone e cose sempre connesse
Storie dal futuro: persone e cose sempre connesseStorie dal futuro: persone e cose sempre connesse
Storie dal futuro: persone e cose sempre connesse
CSP Scarl
 
UN Report: Ethnic Cleansing in the Central African Republic
UN Report: Ethnic Cleansing in the Central African Republic UN Report: Ethnic Cleansing in the Central African Republic
UN Report: Ethnic Cleansing in the Central African Republic
Tawanda Kanhema
 
Il catalogo 2010 Asset CSP
Il catalogo 2010 Asset CSP Il catalogo 2010 Asset CSP
Il catalogo 2010 Asset CSP
CSP Scarl
 
StartupBus UK presentation
StartupBus UK presentationStartupBus UK presentation
StartupBus UK presentation
Cyber-Duck
 
Presentation1
Presentation1Presentation1
Presentation1denapaden
 
CCNA wireless 640 722 Survival Note
CCNA wireless 640 722 Survival NoteCCNA wireless 640 722 Survival Note
CCNA wireless 640 722 Survival Note
Ilham
 
Σχηματοπλανήτης
ΣχηματοπλανήτηςΣχηματοπλανήτης
Σχηματοπλανήτης
Georgios Fesakis
 

Viewers also liked (20)

Getting started with jQuery
Getting started with jQueryGetting started with jQuery
Getting started with jQuery
 
XSS Remediation
XSS RemediationXSS Remediation
XSS Remediation
 
6 Months with WebRTC
6 Months with WebRTC6 Months with WebRTC
6 Months with WebRTC
 
Exploring the Possibilities of Sencha and WebRTC
Exploring the Possibilities of Sencha and WebRTCExploring the Possibilities of Sencha and WebRTC
Exploring the Possibilities of Sencha and WebRTC
 
Pragmatics: Introduction
Pragmatics: IntroductionPragmatics: Introduction
Pragmatics: Introduction
 
Translation Studies
Translation StudiesTranslation Studies
Translation Studies
 
Tripadvisor- PPT
Tripadvisor- PPTTripadvisor- PPT
Tripadvisor- PPT
 
MLA Style Guide
MLA Style GuideMLA Style Guide
MLA Style Guide
 
Retirement Income by KJH Financial Services
Retirement Income by KJH Financial ServicesRetirement Income by KJH Financial Services
Retirement Income by KJH Financial Services
 
How to design for the web
How to design for the webHow to design for the web
How to design for the web
 
Agility at Vietnamworks
Agility at VietnamworksAgility at Vietnamworks
Agility at Vietnamworks
 
Project management at a UX focused digital agency
Project management at a UX focused digital agencyProject management at a UX focused digital agency
Project management at a UX focused digital agency
 
#UBA_#Ciberseguridad_#Cibercrimen_#Privacidad
#UBA_#Ciberseguridad_#Cibercrimen_#Privacidad#UBA_#Ciberseguridad_#Cibercrimen_#Privacidad
#UBA_#Ciberseguridad_#Cibercrimen_#Privacidad
 
Storie dal futuro: persone e cose sempre connesse
Storie dal futuro: persone e cose sempre connesseStorie dal futuro: persone e cose sempre connesse
Storie dal futuro: persone e cose sempre connesse
 
UN Report: Ethnic Cleansing in the Central African Republic
UN Report: Ethnic Cleansing in the Central African Republic UN Report: Ethnic Cleansing in the Central African Republic
UN Report: Ethnic Cleansing in the Central African Republic
 
Il catalogo 2010 Asset CSP
Il catalogo 2010 Asset CSP Il catalogo 2010 Asset CSP
Il catalogo 2010 Asset CSP
 
StartupBus UK presentation
StartupBus UK presentationStartupBus UK presentation
StartupBus UK presentation
 
Presentation1
Presentation1Presentation1
Presentation1
 
CCNA wireless 640 722 Survival Note
CCNA wireless 640 722 Survival NoteCCNA wireless 640 722 Survival Note
CCNA wireless 640 722 Survival Note
 
Σχηματοπλανήτης
ΣχηματοπλανήτηςΣχηματοπλανήτης
Σχηματοπλανήτης
 

Similar to Javascript & jQuery: A pragmatic introduction

Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Raimonds Simanovskis
 
jQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a TreejQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a Treeadamlogic
 
Teaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersTeaching Your Machine To Find Fraudsters
Teaching Your Machine To Find Fraudsters
Ian Barber
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
Shinya Ohyanagi
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
Michelangelo van Dam
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
Michelangelo van Dam
 
Php functions
Php functionsPhp functions
Php functions
JIGAR MAKHIJA
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and Performance
Jonas De Smet
 
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Balázs Tatár
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
Nishan Subedi
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
sartak
 
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
Guilherme Carreiro
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB jhchabran
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretssmueller_sandsmedia
 

Similar to Javascript & jQuery: A pragmatic introduction (20)

Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and JasmineRails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
Rails-like JavaScript Using CoffeeScript, Backbone.js and Jasmine
 
jQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a TreejQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a Tree
 
Bacbkone js
Bacbkone jsBacbkone js
Bacbkone js
 
Teaching Your Machine To Find Fraudsters
Teaching Your Machine To Find FraudstersTeaching Your Machine To Find Fraudsters
Teaching Your Machine To Find Fraudsters
 
Php & my sql
Php & my sqlPhp & my sql
Php & my sql
 
JQuery Flot
JQuery FlotJQuery Flot
JQuery Flot
 
Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2Zend Framework Study@Tokyo #2
Zend Framework Study@Tokyo #2
 
Unit testing with zend framework tek11
Unit testing with zend framework tek11Unit testing with zend framework tek11
Unit testing with zend framework tek11
 
Unit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBeneluxUnit testing with zend framework PHPBenelux
Unit testing with zend framework PHPBenelux
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Php functions
Php functionsPhp functions
Php functions
 
jQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and PerformancejQuery: Tips, tricks and hints for better development and Performance
jQuery: Tips, tricks and hints for better development and Performance
 
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018Let's write secure Drupal code! - DrupalCamp Oslo, 2018
Let's write secure Drupal code! - DrupalCamp Oslo, 2018
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
(Parameterized) Roles
(Parameterized) Roles(Parameterized) Roles
(Parameterized) Roles
 
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
TDC 2014 - JavaScript de qualidade: hoje, amanhã e sempre!
 
jQuery secrets
jQuery secretsjQuery secrets
jQuery secrets
 
Drupal7 dbtng
Drupal7  dbtngDrupal7  dbtng
Drupal7 dbtng
 
Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB Introduction à CoffeeScript pour ParisRB
Introduction à CoffeeScript pour ParisRB
 
international PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secretsinternational PHP2011_Bastian Feder_jQuery's Secrets
international PHP2011_Bastian Feder_jQuery's Secrets
 

Recently uploaded

A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
Philip Schwarz
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
Globus
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
XfilesPro
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
Globus
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
Ortus Solutions, Corp
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
AMB-Review
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Globus
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 

Recently uploaded (20)

A Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of PassageA Sighting of filterA in Typelevel Rite of Passage
A Sighting of filterA in Typelevel Rite of Passage
 
Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
Enhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdfEnhancing Research Orchestration Capabilities at ORNL.pdf
Enhancing Research Orchestration Capabilities at ORNL.pdf
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, BetterWebinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
Webinar: Salesforce Document Management 2.0 - Smarter, Faster, Better
 
GlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote sessionGlobusWorld 2024 Opening Keynote session
GlobusWorld 2024 Opening Keynote session
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdfDominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
Dominate Social Media with TubeTrivia AI’s Addictive Quiz Videos.pdf
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data AnalysisProviding Globus Services to Users of JASMIN for Environmental Data Analysis
Providing Globus Services to Users of JASMIN for Environmental Data Analysis
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 

Javascript & jQuery: A pragmatic introduction

  • 1. Javascript & jQuery A pragmatic introduction November 2014 Ibán Martínez iban@nnset.com www.openshopen.com
  • 3. Data types : Number NO integers, just doubles (double­precision 64­bit format IEEE 754 values) Not called doubles, called number.
  • 4. Data types : Number typeof(37); => 'number' typeof(3.14); => 'number' typeof(Infinity); => 'number'
  • 5. Data types : Number typeof(37); => 'number' typeof(3.14); => 'number' typeof(Infinity); => 'number' Maths disagrees with Javascript : [...] In mathematics, "infinity" is often incorrectly treated as if it were a number. In this context infinity is not itself a quantity but rather a direction or open possibility […] http://en.wikipedia.org/wiki/Infinity
  • 6. Data types : Number 0.1 + 0.2 == 0.3; => false
  • 7. Data types : Number 0.1 + 0.2 == 0.3; => false 0.1 + 0.2; => 0.30000000000000004
  • 8. Data types : Number 0.1 + 0.2 == 0.3; => false 0.1 + 0.2; => 0.30000000000000004 You may 'fix' that issue like this : (0.1 + 0.2).toFixed(2) == 0.3; => true
  • 9. Data types : Number parseInt(3.99); => 3 parseInt('123', 10); => 123 parseInt('11', 2); => 3 Math.floor(3.99); => 3 Math.floor(3.01); => 3 Math.ceil(3.99); => 4 Math.ceil(3.01); => 4 Base to use
  • 10. Data types : Number NaN (Not a Number) ParseInt('hello', 10); => NaN
  • 11. Data types : Number NaN (Not a Number) ParseInt('hello', 10); => NaN NaN + 5; => NaN isNaN(NaN); => true
  • 12. Data types : Number NaN (Not a Number) ParseInt('hello', 10); => NaN NaN + 5; => NaN isNaN(NaN); => true typeof(NaN); ?
  • 13. Data types : Number NaN (Not a Number) ParseInt('hello', 10); => NaN NaN + 5; => NaN isNaN(NaN); => true typeof(NaN); ? typeof (NaN); => 'number'
  • 14. Data types : Number NaN (Not a Number) ParseInt('hello', 10) => NaN NaN + 5 NaN NaN => == NaN isNaN(=> false NaN) => true typeof (NaN) ? typeof (NaN) => 'number'
  • 15. Data types : String They're sequences of Unicode characters with each character represented by a 16­bit number.
  • 16. Data types : String 'hello'.length; => 5 'hello'.charAt(0); => 'h' 'hello, world'.replace('hello', 'goodbye'); => 'goodbye, world' 'hello'.toUpperCase(); => 'HELLO'
  • 17. Data types : String '1' == 1; '1' == parseInt(1); => true '1' == 2; => false '1' === 1; => false
  • 18. Data types : String '1' == 1; '1' == parseInt(1); => true String; 'instanceof 1' == 2; => false string' false '1' === 1; 'my => => false
  • 19. Data types : Boolean false, 0, the empty string (""), NaN, null, and undefined all become false. All other values become true.
  • 20. Data types : null & undefined undefined : declared but not initializated, not an actual value. null : is a value.
  • 21. Data types : null & undefined undefined : declared but not initializated. null : is a value. Be aware of : ( undefined == null ) => true ( null == undefined ) => true
  • 22. Data types : Arrays List of items. var a = new Array(); var a = ['dog', 'cat', 'hen']; typeof a[90]; => undefined a.push('fish'); a.length; => 4
  • 23. Data types : Arrays List of items. .length isn't necessarily the number of items in the array. var a = ['dog', 'cat', 'hen']; a[100] = 'fox'; a.length; => 101 Remember — the length of the array is one more than the highest index.
  • 25. jQuery objects $.fn namespace Methods called on jQuery selections are in the $.fn namespace typeof $('h1'); => 'object' $ namespace Methods in the $ namespace are generally utility­type methods, and do not work with selections. $.each([ 52, 97 ], function( index, value ) { alert( index + ": " + value ); }); http://learn.jquery.com/using­jquery­core/ dollar­object­vs­function/
  • 26. jQuery selectors Class Selector $('.class') http://api.jquery.com/class­selector/ <div class="myClass">Hello</div> <p class="myClass">World</p> <script> $( '.myClass' ).each( function() { $( this ).text( 'Selected' ); }); </script> ID Selector $('#id') http://api.jquery.com/id­selector/ <div id="myId">Hello</div> <script> $( '#myId' ).each( function() { $( this ).text( 'Selected' ); }); </script> $( this ) is the jQuery object that manipulates current DOM item, in this example will be : <div class="myClass"> at first iteration and <p class="myClass"> at second iteration.
  • 27. jQuery selectors Has Attribute Selector [name] http://api.jquery.com/has­attribute­selector/ <div id="myId">Hello</div> <div id="herId">Hello 2</div> <div>No ID</div> <script> $( 'div[id]' ).each( function() { $( this ).text( 'Selected' ); }); </script> Attribute Equals Selector [name="value"] http://api.jquery.com/attribute­equals­selector/ <div> <input type="radio" name="newsletter" value="Cold Fusion"> <input type="radio" name="newsletter" value="Evil Plans"> </div> <script> $( 'input[value=”Evil Plans”]' ).remove(); </script>
  • 28. jQuery CSS manipulation $('').css (getter) http://api.jquery.com/css/ <div style="background­color: blue;">Hello</div> <script> $( 'div[style]' ).each( function() { alert( $(this).css('background­color') ); }); </script> $('').css (setter) <div style="background­color: blue;">Hello</div> <script> $( 'div[style]' ).on( 'mouseover', function() { $(this).css('background­color', red ); }); </script>
  • 29. jQuery CSS manipulation $('').hasClass http://api.jquery.com/hasClass/ <div class='myClass'>Hello</div> <script> $( 'div' ).each( function() { if( $(this).hasClass('myClass') == true ){ … } }); </script> $('').addClass http://api.jquery.com/addClass/ $('').removeClass http://api.jquery.com/removeClass/ <div style="background­color: blue;">Hello</div> <script> $( 'div[style]' ).on( 'mouseover', function() { if( !$(this).hasClass('myClass') ){ $(this).addClass('myClass'); } }); </script>
  • 30. jQuery Events $( document ).ready() The ready event occurs after the HTML document has been loaded. <script> $( document ).ready( function() { console.log( 'HTML is ready!' ); }); </script> $( window ).load() The load event will run once the entire page (images or iframes), not just the DOM, is ready. <script> $( window ).load( function() { console.log( 'All assets and HTML are ready!' ); }); </script> http://learn.jquery.com/using­jquery­core/ document­ready/ http://stackoverflow.com/questions/3698200/window­onload­vs­document­ready
  • 31. jQuery Events Main points for $( document ).ready(): http://stackoverflow.com/a/18339794 ● It will not wait for the images to get loaded. ● Used to execute JavaScript when the DOM is completely loaded. ● Put event handlers here. ● Can be used multiple times. ● Replace $ with jQuery when you receive “$ is not defined.” ● Not used if you want to manipulate images Use $ (window).load() instead.
  • 32. jQuery Events : Trigger & On Fire a custom event using $.fn → trigger() method. <script> $( 'div' ).on( 'mouseover', function() { if( $(this).hasClass('isWinner') ){ $(this).trigger('userHasWon'); } }); </script> Capture a custom event using $.fn → on() method. <script> $( 'div' ).on( 'userHasWon', function( event ) { event.preventDefault(); sendNotificationToServer(); updateTopNavBarWithReward(); }); </script> http://api.jquery.com/trigger/
  • 33. JQuery : AJAX/AJAJ http://api.jquery.com/jquery.ajax/ Asynchronous JavaScript And XML Asynchronous JavaScript And JSON jQuery allows you to perform synchronous requests. synchronous JavaScript And XML synchronous JavaScript And JSON
  • 34. JQuery : AJAX/AJAJ What is AJAX? Web server Get/Post request XML/JSON response Javascript code asks for some data and updates some DOM elements, page is not fully reloaded just partially updated.
  • 35. JQuery : AJAX/AJAJ Asynchronous mode Method calls results can not be collected on natural code sequence order, they may arrive later (asynchronously). So you have to be prepared to process Ajax calls results anytime.
  • 36. JQuery : AJAX/AJAJ Asynchronous mode <form action='http://www.mySite.com/action.php' method='POST'></form> $( 'form' ).on( 'submit', function( event ) { // Do not perform form action until Ajax response is received. event.preventDefault(); var shopName = $('form input[name="shopName"]').val(); checkShopName( shopName ); // Do not perform form action until Ajax response is received. return false; }); function checkShopName( name ) { showSpinner(); performShopNameCheck( name ); }
  • 37. JQuery : AJAX/AJAJ Asynchronous mode function performShopNameCheck( shopName ) { $.ajax({ url : $('form').attr('action'), type: $('form').attr('method'), data: { shop: shopName, domain:'openshopen.com' }, success: function( response ) { var valid = isResponseValid( response ); if( valid ){ // As code sequence was broken before, we may use events // to process results. $('form').trigger('redirectToSuccessPage'); } else{ $('form').trigger('reloadPageWithErrors', response.errors ); } }, error: function( jqXHR , textStatus , errorThrown ){ $('form').trigger('redirectToErrorPage'); } }); }
  • 38. JQuery : AJAX/AJAJ Synchronous mode All code runs in sequence, methods will return values and block sequence until they finish their job.
  • 39. JQuery : AJAX/AJAJ Synchronous mode $( 'form' ).on( 'submit', function( event ) { event.preventDefault(); var shopName = $('form input[name="shopName"]').val(); if( checkShopName( shopName ) ){ redirectToSuccessPage(); } else{ reloadPageWithErrors(); } }); function checkShopName( name ) { showSpinner(); return performShopNameCheck( name ); } Sequence will end up waiting for an AJAX call, some browsers while they are synchronously waiting, do not show DOM changes, so spinner may not be shown to users.
  • 40. JQuery : AJAX/AJAJ Synchronous mode function performShopNameCheck( shopName ) { $.ajax({ url : $('form').attr('action'), type: $('form').attr('method'), data: { shop: shopName, domain:'openshopen.com' }, async : false, success: function( response ) { return isResponseValid( response ); }, error: function( jqXHR , textStatus , errorThrown ){ return false; } }); }
  • 41. JQuery : AJAX/AJAJ Shorthands : POST $.ajax({ type: 'POST', url: 'example.php', data: formData, success: function() { alert( 'success' ); }, done: function() { alert( 'second success' ); }, fail: function() { alert( 'error' ); }, always: function() { alert( 'finished' ); }, }); $.post( 'example.php', formData, function({ alert( 'success' ); }) .done(function() { alert( 'second success' ); }) .fail(function() { alert( 'error' ); }) .always(function() { alert( 'finished' ); }); These are equivalent. http://api.jquery.com/jquery.post/
  • 42. $.ajax({ JQuery : AJAX/AJAJ type: 'GET', url: 'example.php', data: formData, success: function() { alert( 'success' ); }, done: function() { Shorthands : GET alert( 'second success' ); }, fail: function() { alert( 'error' ); }, always: function() { alert( 'finished' ); }, }); $.get( 'example.php', formData, function({ alert( 'success' ); }) .done(function() { alert( 'second success' ); }) .fail(function() { alert( 'error' ); }) .always(function() { alert( 'finished' ); }); http://api.jquery.com/jquery.get/ These are equivalent.
  • 43. Javascript & jQuery A pragmatic introduction November 2014 Ibán Martínez iban@nnset.com https://developer.mozilla.org/en­US/ docs/Web/JavaScript/A_re­introduction_ to_JavaScript http://blog.mgechev.com/2013/02/22/javascript­the­weird­parts/ https://medium.com/@daffl/javascript­the­weird­parts­8ff3da55798e www.openshopen.com http://learn.jquery.com/