Diving into jQuerybasics

Navigate by using the keys
and

If you have worked with JS you have probably seen the$

..in most cases its jQuery..

jQuery basicsWhat the $?

$ == jQuery

The variable $ is an object with a collection of functions to make the life easier for web developers.

jQuery vs Vanilla JavaScriptCSS Appliance

$("#el").css("color", "red")
document.getElementById("el").style = "color: red;"

jQuery vs Vanilla JavaScriptDisabling input elements

$("input").prop('disabled', true);
var inputElements = document.getElementsByTagName("input");

for(var i=0; i<inputElements.length; i++)
{
  inputElements[i].disabled = true;
}

jQuery vs Vanilla JavaScriptX-browser compatible document ready

$(function(){
  // document ready!!
})
var ready = (function(){    

  var readyList,
      DOMContentLoaded,
      class2type = {};
      class2type["[object Boolean]"] = "boolean";
      class2type["[object Number]"] = "number";
      class2type["[object String]"] = "string";
      class2type["[object Function]"] = "function";
      class2type["[object Array]"] = "array";
      class2type["[object Date]"] = "date";
      class2type["[object RegExp]"] = "regexp";
      class2type["[object Object]"] = "object";
      
  var ReadyObj = {
      // Is the DOM ready to be used? Set to true once it occurs.
      isReady: false,
      // A counter to track how many items to wait for before
      // the ready event fires. See #6781
      readyWait: 1,
      // Hold (or release) the ready event
      holdReady: function( hold ) {
          if ( hold ) {
              ReadyObj.readyWait++;
          } else {
              ReadyObj.ready( true );
          }
      },
      // Handle when the DOM is ready
      ready: function( wait ) {
          // Either a released hold or an DOMready/load event and not yet ready
          if ( (wait === true && !--ReadyObj.readyWait) || (wait !== true && !ReadyObj.isReady) ) {
              // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
              if ( !document.body ) {
                  return setTimeout( ReadyObj.ready, 1 );
              }
              
              // Remember that the DOM is ready
              ReadyObj.isReady = true;
              // If a normal DOM Ready event fired, decrement, and wait if need be
              if ( wait !== true && --ReadyObj.readyWait > 0 ) {
                  return;
              }
              // If there are functions bound, to execute
              readyList.resolveWith( document, [ ReadyObj ] );
              
              // Trigger any bound ready events
              //if ( ReadyObj.fn.trigger ) {
              //  ReadyObj( document ).trigger( "ready" ).unbind( "ready" );
              //}
          }
      },
      bindReady: function() {
          if ( readyList ) {
              return;
          }
          readyList = ReadyObj._Deferred();
          
          // Catch cases where $(document).ready() is called after the
          // browser event has already occurred.
          if ( document.readyState === "complete" ) {
              // Handle it asynchronously to allow scripts the opportunity to delay ready
              return setTimeout( ReadyObj.ready, 1 );
          }
          
          // Mozilla, Opera and webkit nightlies currently support this event
          if ( document.addEventListener ) {
              // Use the handy event callback
              document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
              // A fallback to window.onload, that will always work
              window.addEventListener( "load", ReadyObj.ready, false );
              
          // If IE event model is used
          } else if ( document.attachEvent ) {
              // ensure firing before onload,
              // maybe late but safe also for iframes
              document.attachEvent( "onreadystatechange", DOMContentLoaded );
              
              // A fallback to window.onload, that will always work
              window.attachEvent( "onload", ReadyObj.ready );
              
              // If IE and not a frame
              // continually check to see if the document is ready
              var toplevel = false;
              
              try {
                  toplevel = window.frameElement == null;
              } catch(e) {}
              
              if ( document.documentElement.doScroll && toplevel ) {
                  doScrollCheck();
              }
          }
      },
      _Deferred: function() {
          var // callbacks list
              callbacks = [],
              // stored [ context , args ]
              fired,
              // to avoid firing when already doing so
              firing,
              // flag to know if the deferred has been cancelled
              cancelled,
              // the deferred itself
              deferred  = {
              
                  // done( f1, f2, ...)
                  done: function() {
                      if ( !cancelled ) {
                          var args = arguments,
                              i,
                              length,
                              elem,
                              type,
                              _fired;
                          if ( fired ) {
                              _fired = fired;
                              fired = 0;
                          }
                          for ( i = 0, length = args.length; i < length; i++ ) {
                              elem = args[ i ];
                              type = ReadyObj.type( elem );
                              if ( type === "array" ) {
                                  deferred.done.apply( deferred, elem );
                              } else if ( type === "function" ) {
                                  callbacks.push( elem );
                              }
                          }
                          if ( _fired ) {
                              deferred.resolveWith( _fired[ 0 ], _fired[ 1 ] );
                          }
                      }
                      return this;
                  },
                  
                  // resolve with given context and args
                  resolveWith: function( context, args ) {
                      if ( !cancelled && !fired && !firing ) {
                          // make sure args are available (#8421)
                          args = args || [];
                          firing = 1;
                          try {
                              while( callbacks[ 0 ] ) {
                                  callbacks.shift().apply( context, args );//shifts a callback, and applies it to document
                              }
                          }
                          finally {
                              fired = [ context, args ];
                              firing = 0;
                          }
                      }
                      return this;
                  },
                  
                  // resolve with this as context and given arguments
                  resolve: function() {
                      deferred.resolveWith( this, arguments );
                      return this;
                  },
                  
                  // Has this deferred been resolved?
                  isResolved: function() {
                      return !!( firing || fired );
                  },
                  
                  // Cancel
                  cancel: function() {
                      cancelled = 1;
                      callbacks = [];
                      return this;
                  }
              };
              
          return deferred;
      },
      type: function( obj ) {
          return obj == null ?
              String( obj ) :
              class2type[ Object.prototype.toString.call(obj) ] || "object";
      }
  }
  // The DOM ready check for Internet Explorer
  function doScrollCheck() {
      if ( ReadyObj.isReady ) {
          return;
      }
      
      try {
          // If IE is used, use the trick by Diego Perini
          // http://javascript.nwbox.com/IEContentLoaded/
          document.documentElement.doScroll("left");
      } catch(e) {
          setTimeout( doScrollCheck, 1 );
          return;
      }
      
      // and execute any waiting functions
      ReadyObj.ready();
  }
  // Cleanup functions for the document ready method
  if ( document.addEventListener ) {
      DOMContentLoaded = function() {
          document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
          ReadyObj.ready();
      };
      
  } else if ( document.attachEvent ) {
      DOMContentLoaded = function() {
          // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
          if ( document.readyState === "complete" ) {
              document.detachEvent( "onreadystatechange", DOMContentLoaded );
              ReadyObj.ready();
          }
      };
  }
  function ready( fn ) {
      // Attach the listeners
      ReadyObj.bindReady();
      
      var type = ReadyObj.type( fn );
      
      // Add the callback
      readyList.done( fn );//readyList is result of _Deferred()
  }
  return ready;
})();

ready(function(){
  // document ready!!
})

There is a difference!$(window).load != $(document).ready

load is called when all assets are done loading, including images.
ready is fired when the DOM is ready for interaction.

jQuery basicsSelectors

Basic selectorsSimple css selectors

$('div, p, h1')                       // Element selector

$('#myElement')                       // Id selector

$('.myElements')                      // Class selector

$('input[name="inputField"]')         // Attribute selector

$('ul li:first')                      // Pseudo selectors

$('table tr:first td:first')

Basic selectors

HTML

<div>
    <h3 id="header">SAMUEL L. IPSUM</h3>
    <a href="http://slipsum.com/">http://slipsum.com/</a>
    <p>
      Now that there is the Tec-9, a crappy spray gun from South Miami. 
      This gun is advertised as the most popular gun in American crime. 
      Do you believe that shit?
    </p> 
    <p>
      It actually says that in the little book
      that comes with it: the most popular gun in American crime. Like 
      they're actually proud of that shit. 
    </p>
</div>

<script>
  $("h1, a, p").addClass("red-border")
</script>

Result

http://slipsum.com/

Now that there is the Tec-9, a crappy spray gun from South Miami. This gun is advertised as the most popular gun in American crime. Do you believe that shit?

It actually says that in the little book that comes with it: the most popular gun in American crime. Like they're actually proud of that shit.

Basic selectors

HTML

<div class="container">
    <h3 id="header">SAMUEL L. IPSUM</h3>
    <a href="http://slipsum.com/">http://slipsum.com/</a>
    <p>
      Now that there is the Tec-9, a crappy spray gun from South Miami. 
      This gun is advertised as the most popular gun in American crime. 
      Do you believe that shit?
    </p> 
    <p>
      It actually says that in the little book
      that comes with it: the most popular gun in American crime. Like 
      they're actually proud of that shit. 
    </p>
</div>

<script>
  $("#header").addClass("red-border")
</script>

Result

http://slipsum.com/

Now that there is the Tec-9, a crappy spray gun from South Miami. This gun is advertised as the most popular gun in American crime. Do you believe that shit?

It actually says that in the little book that comes with it: the most popular gun in American crime. Like they're actually proud of that shit.

Basic selectors

HTML

<div class="container">
    <h3 id="header">SAMUEL L. IPSUM</h3>
    <a href="http://slipsum.com/">http://slipsum.com/</a>
    <p>
      Now that there is the Tec-9, a crappy spray gun from South Miami. 
      This gun is advertised as the most popular gun in American crime. 
      Do you believe that shit?
    </p> 
    <p>
      It actually says that in the little book
      that comes with it: the most popular gun in American crime. Like 
      they're actually proud of that shit. 
    </p>
</div>

<script>
  $(".container").addClass("red-border")
</script>

Result

http://slipsum.com/

Now that there is the Tec-9, a crappy spray gun from South Miami. This gun is advertised as the most popular gun in American crime. Do you believe that shit?

It actually says that in the little book that comes with it: the most popular gun in American crime. Like they're actually proud of that shit.

Basic selectors

HTML

<table>
  <tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>

<script>
  $("table tr:first td:first").addClass("red-content")
</script>

Result

Basic selectors

HTML

<table>
  <tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
  <tr>
    <td></td>
    <td></td>
    <td></td>
    <td></td>
  </tr>
</table>

<script>
  $("table tr:last td:last").addClass("red-content")
</script>

Result

Basic selectors

HTML

<div>John Resig</div>
<div>George Martin</div>
<div>Malcom John Sinclair</div>
<div>J. Ohn</div>

<script>
  $( "div:contains('John')" ).addClass("red-border")
</script>

Result

John Resig
George Martin
Malcom John Sinclair
J. Ohn

jQuery basicsEvents

What isEvent driven programming?

...In computer programming, event-driven programming or event-based programming is a programming paradigm in which the flow of the program is determined by events—e.g., sensor outputs or user actions (mouse clicks, key presses)...

Events are the beating heart of any JavaScript application

This is eventdriven programming

// Say hey when the click event is fired!
$("a").click(function(){
  alert("hey!"):
});

Do this when that happens

jQuery EventsDocument events

$(function(){      

  // Same as $(function(){...})
  $(document).ready(function(){         
    console.log("document ready!");
  })
  
  // $(window).load(...) Deprecated v 1.8, use:
  $(window).on('load', function(){            
    console.log("All assets loaded!");
  })
  
})

jQuery EventsBrowser events

$(function(){

  $(window).on("resize", function(){
    console.log("resize");
  });
  
  $(".browser-event-page").on("scroll", function(){
    console.log("scroll");
  });
  
})

jQuery EventsMouse events

$(function(){
  var mouseEvents = [
    "click", 
    "dblclick", 
    "focusout", 
    "hover", 
    "mousedown", 
    "mouseenter", 
    "mouseleave", 
    "mousemove", 
    "mouseout", 
    "mouseover", 
    "mouseup", 
    "toggle"
  ];
  
  for(var i = 0; i < mouseEvents.length; i++){
    (function(eventName){
      $("#mouse-event-box").on(eventName, function(){
        console.log(eventName);
      })
    })(mouseEvents[i]);
  }
})

jQuery EventsKeyboard events

$(function(){

  var keyBoardEvents = [
    "keydown", 
    "keypress", 
    "keyup"
  ];
  
  for(var i = 0; i < keyBoardEvents.length; i++){
    (function(eventName){
      $("#keyboard-event-box").on(eventName, function(){
        console.log(eventName);
      })
    })(keyBoardEvents[i]);
  }
})

jQuery EventsForm events




$(function(){

  var formEvents = [
    "blur", 
    "change", 
    "focus", 
    "submit"
  ];
  
  for(var i = 0; i < formEvents.length; i++){
    (function(eventName){
      $("#form-event-box, #form-event-box :input").on(eventName, function(e){
        console.log(eventName);
        e.preventDefault();
        e.stopPropagation();
      })
    })(formEvents[i]);
  }
})

jQuery basicsAjax

jQuery AjaxAsynchronous JavaScript and XML

// Get the html content of vg.no
$.ajax({
  url: "http://vg.no/"
}).done(function(res){
  console.log(res);
});
// Get the html content of vg.no
var url = "http://vg.no";
var xhr;

if(typeof XMLHttpRequest !== 'undefined'){
  xhr = new XMLHttpRequest();      
} 
else {
  var versions = [
    "MSXML2.XmlHttp.5.0", 
    "MSXML2.XmlHttp.4.0",
    "MSXML2.XmlHttp.3.0", 
    "MSXML2.XmlHttp.2.0",
    "Microsoft.XmlHttp"
  ];
  
  for(var i = 0, len = versions.length; i < len; i++) {
    try {
      xhr = new ActiveXObject(versions[i]);
      break;
    }catch(e){}
  }
}

xhr.onreadystatechange = function() {
  if(xhr.readyState < 4) {
    return;
  }
  
  if(xhr.status !== 200) {
    console.log("Not OK!", xhr.status);
  }
  
  // all is well  
  if(xhr.readyState === 4) {
    console.log(xhr.response);
  }     
}

xhr.open('GET', url, true);
xhr.send('');

Ajax eventsShorthands

  • jQuery.get()
  • jQuery.getJSON()
  • jQuery.getScript()
  • jQuery.post()
  • .load()

Ajax eventsShorthands

/**
 *  Shorthand functions
 */ 
 
// $.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
$.get("example.php", function() {
  alert( "success" );
})




// $.getJSON( url [, data ] [, success( data, textStatus, jqXHR ) ] )
$.getJSON( "ajax/test.json", function( data ) {
  alert( "success" );
});




// $.getScript( url [, success(script, textStatus, jqXHR) ] )
$.getScript( "ajax/test.js", function( data, textStatus, jqxhr ) {
  alert( "success" );
});



// $.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
$.post( "ajax/test.html", function( data ) {
  $( ".result" ).html( data );
});

/**
 *  Equivalent ajax call
 */ 
 
// $.get( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
$.ajax({
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

// $.getJSON( url [, data ] [, success( data, textStatus, jqXHR ) ] )
$.ajax({
  dataType: "json",
  url: url,
  data: data,
  success: success
});

// $.getScript( url [, success(script, textStatus, jqXHR) ] )
$.ajax({
  url: url,
  dataType: "script",
  success: success
});

// $.post( url [, data ] [, success(data, textStatus, jqXHR) ] [, dataType ] )
$.ajax({
  type: "POST",
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

Ajax events.load

// Load the content from "ajax/test.html" into the #result
$( "#result" ).load( "ajax/test.html", function() {
  alert( "Load was performed." );
});


// Load the content from the #container in "ajax/test.html" into the #result
$( "#result" ).load( "ajax/test.html #container" );

Pretty nifty!

Ajax eventsGlobal Ajax event handlers

    // Show a message when an Ajax requests have started.
    $( document ).ajaxStart(function() {
      $( "#msg" ).append( "<li>Ajax request started</li>" );
    });
    
    // Show a message before an Ajax request is sent.
    $( document ).ajaxSend(function( event, request, settings ) {
      $( "#msg" ).append( "<li>Sending request at " + settings.url + "</li>" );
    });
    
    // Show a message when an Ajax request completes successfully.
    $( document ).ajaxSuccess(function( event, request, settings ) {
      $( "#msg" ).append( "<li>Successful Request!</li>" );
    });
    
    // Show a message when an Ajax request fails.
    $( document ).ajaxError(function( event, request, settings ) {
      $( "#msg" ).append( "<li>Error requesting page " + settings.url + "</li>" );
    });
    
    // Show a message when an Ajax request completes.
    $( document ).ajaxComplete(function( event,request, settings ) {
      $( "#msg" ).append( "<li>Request Complete.</li>" );
    });
    
    // Show a message when an Ajax requests have stopped.
    $( document ).ajaxStop(function() {
      $( "#msg" ).append( "<li>Ajax request stopped</li>" );
    });
    

    jQuery basicsAnimations

    Why you should avoid jQuery's animate

    Conclusion:Use CSS3 transitions whenever possible.

    HTML

    <div class="container">
      <div id="animation-square"></div>
    </div>
    <style>
      .container {
        position: relative;
        width: 100%;
        min-height: 100px;
      }
      #animation-square {
        height: 20px;
        width:20px;
        background: red;
        
        transition: all 1s ease;
      }
      #animation-square.big {
        height: 150px;
        width:150px;
        background: blue;
        -webkit-transform: rotate(90deg);
      }
      
    </style>
    <script>
      (function(){
      
        var $animationSquare = $("#animation-square");
        $animationSquare.click(function(){
          $animationSquare.toggleClass("big");
        })
        
      })();
    </script>

    Result

    HTML

    <div class="container">
      <div id="jq-square"></div>
    </div>
    <style>
      .container {
        position: relative;
        width: 100%;
        min-height: 100px;
      }
      #jq-square {
        height: 20px;
        width:20px;
        background: red;
      }
      
    </style>
    <script>
      (function(){
      
        var $animationSquare = $("#jq-square");
        $animationSquare.click(function(){
        
          var targetSize = $animationSquare.outerHeight() > 20 ? 20 : 150;
          
          var state = {
            width: targetSize + "px",
            height: targetSize + "px",
            color: targetSize == 20 ? "red" : "blue"
          };
          
          $animationSquare.animate(state)
        })
        
      })();
    </script>

    Result

    Hidden gems

    • $.extend(...)
    • $.map(...)
    • $.merge(...)

    Hidden gems$.extend(...)

    var options = {
      width: 100,
      height: 100
    }
    
    var otherOptions = {
      x: 0,
      y: 0
    }
    
    $.extend(options, otherOptions);
    
    /* Extends the options object with the x, y properties from the other options:
    
      options = {
        width: 100,
        eight: 100,
        x: 0,
        y: 0
      }
      
    */

    Hidden gems$.map(...)

    var numbers = [0,1,2,3,4,5,6,7,8,9];
    
    // Get all the even numbers
    var evens = $.map(numbers, function(val){
      return val % 2 == 0 ? val : null;
    });
    
    /* 
      Maps the values from the array, based on the condition sendt as the second argument. 
      If null is returned, the value is not mapped; else the value is pushed on to the result array. 
      
      evens = [0, 2, 4, 6, 8]
      
    */

    Hidden gems$.merge(...)

    var first = [ "a", "b", "c" ],
        second = [ "d", "e", "f" ];
        
    $.merge(first, second);
    
    /* 
      Merges two arrays, altering the first argument.
      
      first = [ "a", "b", "c", "d", "e", "f" ]
      
    */

    jQuery basicsPlugins

    jQuery pluginsCreating a basic plugin

    // Definition:
    $.fn.greenify = function() {
        this.css( "color", "green" );
    };
    
    $( "a" ).greenify(); // Makes all the links green.

    jQuery pluginsChaining

    $.fn.greenify = function() {
      this.css( "color", "green" );
      return this;
    }
    
    $( "a" ).greenify().addClass( "greenified" );

    jQuery pluginsPlugin template

    (function ( $ ) {
    
        $.fn.greenify = function( options ) {
        
            // This is the easiest way to have default options.
            var settings = $.extend({
                // These are the defaults.
                color: "#556b2f",
                backgroundColor: "white"
            }, options );
            
            // Greenify the collection based on the settings variable.
            return this.css({
                color: settings.color,
                backgroundColor: settings.backgroundColor
            });
            
        };
        
    }( jQuery ));
    
    // Example usage:
    $( "div" ).greenify({
      color: "orange"
    });

    That's all folks!TY!

    @myrlandnu