SlideShare a Scribd company logo
1 of 43
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

Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»Юрий Буянов «Squeryl — ORM с человеческим лицом»
Юрий Буянов «Squeryl — ORM с человеческим лицом»
e-Legion
 
Instant Dynamic Forms with #states
Instant Dynamic Forms with #statesInstant Dynamic Forms with #states
Instant Dynamic Forms with #states
Konstantin Käfer
 

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

Tripadvisor- PPT
Tripadvisor- PPTTripadvisor- PPT
Tripadvisor- PPT
Elisabeth
 
MLA Style Guide
MLA Style GuideMLA Style Guide
MLA Style Guide
clover66
 
Presentation1
Presentation1Presentation1
Presentation1
denapaden
 

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

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
adamlogic
 
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 Secrets
smueller_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

%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
masabamasaba
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Medical / Health Care (+971588192166) Mifepristone and Misoprostol tablets 200mg
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
shinachiaurasa2
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
VictoriaMetrics
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
9953056974 Low Rate Call Girls In Saket, Delhi NCR
 

Recently uploaded (20)

WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Knoxville Psychic Readings, Attraction spells,Br...
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
%in kaalfontein+277-882-255-28 abortion pills for sale in kaalfontein
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
Devoxx UK 2024 - Going serverless with Quarkus, GraalVM native images and AWS...
 
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
Large-scale Logging Made Easy: Meetup at Deutsche Bank 2024
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park %in ivory park+277-882-255-28 abortion pills for sale in ivory park
%in ivory park+277-882-255-28 abortion pills for sale in ivory park
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 

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/