jQuery - 101

What is jQuery?

Why bother learning jQuery?

  • DOM Manipulation & Traversing
  • Selector & Filters
  • Event Handling
  • AJAX
  • Utility Methods

DOM Manipulation

  • Insertion
    • Around
    • Inside
    • Outside
  • Removal
  • Replacement
  • Copy
  • General
  • Classes

DOM Manipulation: Insertion

  • Around
    • .wrap()
    • .unwrap()
    • .wrapAll()
    • .wrapInner()
  • Inside
    • .append()/.appendTo()
    • .prepend()/.prependTo()
    • .html()
    • .text()
  • Outside
    • .before()/.insertBefore()
    • .after()/.insertAfter()

DOM Manipulation: Removal

  • .detach()
  • .empty()
  • .remove()
  • .unwrap()

DOM Manipulation: Replacement

  • .replace()/.replaceWith()

DOM Manipulation: Copy

  • .clone()

DOM Manipulation: General

  • .attr()/.removeAttr()
  • prop()/.removeProp()
  • .val()

DOM Manipulation: Classes

  • .addClass()/.removeClass()
  • .toggleClass()
  • .hasClass()

Selectors

  • Basic
  • Hierarchy
  • Attribute

Selectors: Basic

  • All
  • Class
  • ID
  • Element
  • Multiple

Selectors: Hierarchy

  • Child
  • Descendent
  • Next Adjacent
  • Next Sibling

Selectors: Attribute

  • Contains Prefix
  • Contains
  • Contains Word
  • Ends With
  • Equals To
  • Not Equals To
  • Starts With
  • Has
  • Multiple

Events

  • Browser/Document
  • Mouse
  • Keyboard
  • Form

Events: Browser/Document

  • .resize()
  • .scroll()
  • .ready()

Events: Mouse

  • .click()/.dblClick()
  • .mouseEnter()/.mouseLeave()
  • .mouseUp()/.mouseDown()
  • .hover()
  • .mouseOver()

Events: Keyboard

  • .keyUp()
  • .keyDown()
  • .keyPress()

Events: Forms

  • .focus()/.focusIn()/.focusOut()/
  • .blur()
  • .change()
  • .select()
  • .submit()

Events: How to attach an event?

  • .bind()/.unbind()
  • .delegate()/.undelegate()
  • .on()/.off()

AJAX

  • .ajax()
  • Global Methods
  • Shorthand Methods

AJAX: .ajax()

  • Returns jqXHR (jQuery XML HTTP Request) Object
  • jqXHR contains .done(), .fail(), .always(), .then() methods.
  • Attributes:
    • data
    • contentType
    • dataType
    • method

AJAX: Global Methods

  • .ajaxSend()/.ajaxComplete()
  • .ajaxStart()/.ajaxStop()
  • .ajaxError()/.ajaxSuccess()

AJAX: Shorthand Methods

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

Utility Methods

  • .each()
  • .extend()
  • isArray()/isFunction()/isNumeric()/.isPlainObject()
  • .unique()
  • .parseJSON()/.parseHTML()
  • .merge()
  • makeArray()

Best Practices

Ready Event

 $("document").ready(function() {
    // The DOM is ready!
    // The rest of the code goes here
  });
 $(function() {
    // The DOM is ready!
    // The rest of the code goes here
  });

You might do it like this:

or this:

This is fine, if

  • you don't care about page load performance.
  • you don't care about best practices.
  • you really want to go home early.

Best Practice

// IIFE - Immediately Invoked Function Expression
  (function($, window, document) {

    // The $ is now locally scoped 

   // Listen for the jQuery ready event on the document
   $(function() {

     // The DOM is ready!

   });

   // The rest of the code goes here!

  }(window.jQuery, window, document));
  // The global jQuery object is passed as a parameter

DOM Manipulation

you might do it like this:


  // sets an element's title attribute using it's current text
  $(".container input#elem").attr("title", $(".container input#elem").text());

  // sets an element's text color to red
  $(".container input#elem").css("color", "red");

  // makes the element fade out
  $(".container input#elem").fadeOut();

this is okay, if

  • you want to repeat yourself to death.
  • you don't care about either best practices or performance.

Best Practice

  // cache the live DOM element inside of a variable
  var elem = $("#elem");

  // sets an element's title attribute using it's current text
  elem.attr("title", elem.text());

  // sets an element's text color to red
  elem.css("color", "red");

  // makes the element fade out
  elem.fadeOut();
	

  // alternate way via chaining. P.S. It does looks messy.
  elem
    .attr("title", elem.text())
    .css("color", "red")
    .fadeOut();

Event Handling

you might do it like this:

$("#longlist li").on("mouseenter", function() {
    $(this).text("Click me!");
});

$("#longlist li").on("click", function() {
    $(this).text("Why did you click me?!");
});

$('.class').click(function(){
    $(this).text("Why did you click me?!");
})

this is super cool, if

  • you really like eating lots of lots of memory
  • you have like 4-5 DOM elements
  • again, you don't care about best practices

Best Practice

// cache the target element's parent first
var list = $("#longlist");

list.on("mouseenter", "li", function(){
    $(this).text("Click me!");
});

list.on("click", "li", function() {
    $(this).text("Why did you click me?!");
});

// delegate event via parent, like a boss.

AJAX

You might do it like this:

  $.ajax({
      url: "getName.php",
      type: "get",
      data: {
          foo: 'bar'
      },
      success: function(data) {
        // updates the UI based the ajax result
        $(".person-name").text(data.name);  
      }
  });

this is awesome, if

  • you like inflexible code.
  • you have like 1-2 total ajax requests.
  • you want to go home but PM wants it done today.

Best Practice

function getName(personid) {
    var dynamicData = {};
    dynamicData["foo"] = personID;
    return $.ajax({
      url: "getName.php",
      type: "get",
      data: dynamicData
    });
  }

  getName("2342342").done(function(data) {
    // updates the UI based the ajax result
    $(".person-name").text(data.name); 
  });

THE END.

jQuery - 101

By Umayr Shahid

jQuery - 101

For a jQuery beginner level workshop. Credits to Greg Franko for best practices.

  • 611