43
Javascript & jQuery A pragmatic introduction November 2014 Ibán Martínez [email protected] www.openshopen.com

Javascript & jQuery: A pragmatic introduction

Embed Size (px)

Citation preview

Javascript & jQueryA pragmatic introduction

November 2014

Ibán Martí[email protected]

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 disagreesdisagrees 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 : NumberNaN (Not a Number)

ParseInt('hello', 10);=> NaN

Data types : NumberNaN (Not a Number)

ParseInt('hello', 10);=> NaN

NaN + 5;=> NaN

isNaN(NaN);=> true

Data types : NumberNaN (Not a Number)

ParseInt('hello', 10);=> NaN

NaN + 5;=> NaN

isNaN(NaN);=> true

typeof(NaN);?

Data types : NumberNaN (Not a Number)

ParseInt('hello', 10);=> NaN

NaN + 5;=> NaN

isNaN(NaN);=> true

typeof(NaN);?

typeof (NaN); => 'number'

Data types : NumberNaN (Not a Number)

ParseInt('hello', 10)=> NaN

NaN + 5=> NaN

isNaN(NaN)=> true

typeof (NaN)?

typeof (NaN) => 'number'

NaN == NaN

=> false

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

'1' == 2; => false

'1' === 1; => false'my 

string' 

instance

of Strin

g;

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

jQueryhttp://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 selectorsClass 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 selectorsHas 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 EventsMain 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

<script>

  $( 'div' ).on( 'mouseover', function() {    if( $(this).hasClass('isWinner') ){      $(this).trigger('userHasWon');    }  });</script>

Fire a custom event using $.fn   → trigger() method.

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/AJAJhttp://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/AJAJWhat is AJAX?

Web server

Javascript code asks for some dataand updates some DOM elements, page isnot fully reloaded just partially updated.

Get/Post request

XML/JSON response

JQuery : AJAX/AJAJAsynchronous 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/AJAJAsynchronous 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/AJAJAsynchronous 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/AJAJSynchronous mode

All code runs in sequence, methods will return values and block sequence until 

they finish their job.

JQuery : AJAX/AJAJSynchronous 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/AJAJSynchronous 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/AJAJShorthands : 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({type: 'GET',url: 'example.php',data: formData,success: function() {

alert( 'success' );},done: function() {

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

JQuery : AJAX/AJAJShorthands : GET

http://api.jquery.com/jquery.get/

These are equivalent.

Javascript & jQueryA pragmatic introduction

November 2014

Ibán Martí[email protected]

www.openshopen.com

https://developer.mozilla.org/en­US/docs/Web/JavaScript/A_re­introduction_to_JavaScripthttp://blog.mgechev.com/2013/02/22/javascript­the­weird­parts/https://medium.com/@daffl/javascript­the­weird­parts­8ff3da55798e

http://learn.jquery.com/