2/8/2018 - 8:28 PM

jQuery Essential

Learning to use jQuery

Using jQuery

  • Download jQuery and include it in the root of your project
  • Inside the head element of the html page, load jquery: <script src="jquery-3.0.0.js"></script>
  • To reference the jquery library, use: $
  • Test a page load using jquery:
  $("document").ready(function() {
    $("#content").append("<p>The page has just loaded</p>");
  $("document").ready(function() { }); == $(function() { });
  • Jquery for the document, add an event listener to the document called ready, pass in an anonymous function that will execute on page load, which will jquery for an element on the page with an id(#) of content and append a paragraph element that contains some text.
  • There is a load event listener, but load waits for the whole page, including images to fully load before firing any events, ready doesn't wait and thus occurs faster.


  • A page cannot be manipulated safely UNTIL the document is "ready"
  • Code that is inside $(document).ready() will only run after the page's DOM is loaded (all of its elements have been loaded on the page)
  • There is also a jQuery function that will load the DOM until after all images are loaded, which won't happen with the regular document.ready: $(window).load(function() {})


  • $("p").css("border", "3px, solid red"); will return a matched set of all <p> tags and apply a style using .css method of red border.
  • $(".selectors").css(...): will select all class elements with .selectors and apply the css rule
  • You can perform the same for an element with an id selector.


  • are used to refine the results that come back from selectors
  • $("p:first").css(...): will select the first <p> element to apply css styles
  • $("h2:not(.selectors)"): select <h2> tags that do not have class .selectors to apply css
  • Other examples of filters:
    • :first, :last
    • :even, :odd: even or odd items that are in the matched set (array)
    • :gt(), :lt(), :eq(): items gt, lt or eq to an index in the matched set (array)
    • :animated(): items in the process of being animated
    • :focus(): element that currently has the focus
    • :not(expression): elements that don't match the expression $("#example p:not(p:eq(2))"): par e lement that is not at index 2

Selecting and Filtering with Attributes

$("document").ready(function() {
  //selects all p elements WITH a class, doesn't matter what class, just a class
  $("p[class]").css("border", "3px solid red");
  //selecting with a certain attribute value
  $("p[id=par1]").css("border", "3px solid red");
  //selecting with a certain attribute value that starts with (^=)
  $("p[id^=para").css("border", "3px solid red");
  //certain attribute that starts with and contains (*=)
  $("p[id^=para][lang*=en-]").css("border", "3px solid red");
  //selecting elements that contain a specified string in its content
  //selecting elements that are parents(have child element(s) under them or text nodes)
  //Advanced search using has
  //CHILD FILTERS (denoted with a space)
  //selects the p elements who are 1st children of a div
  $("div p:first-child").css(...);
  //selects the last type (p) of a div
  $("div p:last-of-type").css(...);
  //selects the n-th child
  $("div p:nth-child(3)").css(...);
  $("div p:nth-child(2n)").css(...); //selects every even or 2n element
  //you can replace the arguement with any expression involving n

Traversing the DOM

$("document").ready(function() {

  //Applies css to all the child elements of the targeted #example 
  //Target previous, next and parent elements of a referenced element
  var elem = $("#para1"); //referenced element
  elem.parents().css(...); //This will apply css to all parents, including the HTML parent
  //To limit the parent search, for example, until the <body> tag, not including the <body> tag:
  //find will search down the tree starting at the #example and matches #para4 
  //Iterating over each jquery wrapped element
  var l_margin = 0;
  var border = 3;
  $("#example p").each(function(index, element) { //element is a DOM object
    $(element).css("border", border+"px solid red") //need to convert DOM object to jquery 
                                                    //object by wrapping DOM element in jquery
    .css("margin-left", l_margin);
    border += 2;
    l_margin += 10;

Creating Content

  • var newPara = $("<p>");: jquery to create a new paragraph element, as part of the DOM but not yet inserted into the page
  • newPara.append("<em>Hello there!</em>");: add content to the newly created element

//Creating an element with attributes:
$('<div>', {
  id: 'id',
  class: 'class',
  html: 'some Text'

//OR using javascript and then converting to jQuery:
var e = document.createElement('div'); = 'id';
e.class = 'class';
e.innerHTML = 'some Text';

var $e = $(e);

Changing Content

  • $("#content").html(newPara);: html function will replace the existing html of the element with id of content with the the argument provided.
  • $("#creation").prepend("New text!");: prepend will add the argument in front of the content with the element with id of creation.

Inserting Content

  • To insert content within an element, use .append to place the new content right after the existing one, or .prepend to place new content before the existing one.
  • To place content before or after an element:
// <p>This is a paragraph.</p>

//using before or insertBefore:
$("p").before("<p>New Content</p>");
$("<p>New Content</p>").insertBefore("p");
//RESULTS: <p>New Content</p><p>This is a paragraph.</p>

//using after or insertAfter:
$("p").after("<p>New Content</p>");
$("<p>New Content</p>").insertAfter("p");
//RESULTS: <p>This is a paragraph.</p><p>New Content</p>

Altering Page Content

$("document").ready(function() {
  //wrap EACH p in #element in a div and change the font color to red
  $("#example p").wrap("<div style='color: red'/>");
  //wrap ALL of the p elements in 1 div
  $("#example p").wrapALL("<div style='color: red' ?>");
  //empty the contents of an element
  //remove: removes elements AND detaches embedded data and event handlers
  $("#example p.a, #example p.b").remove();
  //detach: removes elements BUT keeps embedded data and event handlers
  //in case the elements are put back into the DOM
  $("#example p.a, #example p.b").detach();
  //replaceAll: in this case replaces all p with an id inside of #example
  //with the newly added div
  $("<div>replaced</div>").replaceAll("#example p[id]");
  //replaceWith: similar to replaceAll (reversing args)
  $("#example p[id]").replaceWith("</div>replaced</div>");
  //ALSO, you can use a callback function:
  $("#example p[id]").replaceWith(replacementFn);

function replacementFn() {
  //each element that $("#example p[id]") returns will be yeided as this
  //need to wrap DOM this into $(this)
  if ( $(this).text().indexOf("1" != -1) ) {
    return "<p>This is par uno.</p>";
  } else {
    return this.outerHTML;

Working with CSS (methods)

  • hasClass(className)
  • addClass(className)
  • removeClass(className)
  • toggleClass(className)
    • this function just removes or adds className to the elment!

Event Handling in jQuery

//When the browser is loaded, attach these events to the element with an id of example
$("document").ready(function() {
  //on the event "mousemove" and "click", apply the following callback functions
  $("#example").on("mousemove", onMouseOver);
  $("#example").on("click", onMouseClick);


function onMouseOver(evt) {
  //the evt or event object becomes available to use
  //contains information about the event that just occured 
  $("#example").text(evt.type + ": " + evt.pageX + ", " + evt.pageY + "\n");

//Binding events:
$(function() {
  $("").on("mouseover mouseleave", highlight); //highlight = callback function
  //To remove the .on event, use .off:
  $("").off("mouseover mouseleave", highlight);

Animations using jQuery

$("document").ready(function() {
  $("#go").click(function() { //button that has a click event handler attached
    $("#testDiv").animate({width: 400}, 300) //animate( {property:value, ...}, time in ms)
    .animate( {height: 300}, 400) //chaining on multiple animation calls
    .animate( {top: "+=100", borderWidth: 10}, "slow") //"+=100" means take current top value and 
                                                       //and all 100 pixels to it
  $("").click(function() {
    $().hide(1000, swing); //swing has a more natural feel than using linear
  $("").click(function() {
  $("").click(function() {
    $().toggle("slow"); //toggle if hide then show, if show then hide

AJAX in jQuery

  • AJAX, ajax(): used to perform generic AJAX requests
  • load: loads AJAX content directly into a page element, using .ajax
$("document").ready(function() {
  $("#button1").click(getContent); //attaching click events to these two buttons and passing
                                   //in two callback functions

function getContent() {
  $.ajax("path to a file in the directory OR URL", 
      success: setContent, //callback function on successful ajax request
      type: "GET",  //type of HTTP request, ex. "POST"
      dataType: "text"  //datatype of return value

function setContent(data, status, jqxhr) {
//data =  return value from the ajax request
  //jquery for the element and place the text returned from the request inside this element

//Both the getContent and setContent methods can be replaced by the load ajax call
//which performs the ajax get request and sets the content into the specified element:

function loadHTML() {
  $("#example").load("path to file or url");

//In your ajax call, you'll need to declare the url, type, datatype, success, error
//and optionally a complete function that gets execute regardless if on success or error:

  url: '',
  type: 'GET',
  dataType: 'text',
  success: function() {}, //or successFN
  error: function() {}, //or errorFN
  complete: function() { console.log("Completed!") }

function successFn(result){ //the result of the request is sent here
  //code block 

function errorFn(xhr, status, strErr){ //Handy args
  //code block

//jQuery provides shorthand methods, for example: $.load(), $.getJSON(), $.post(), $.get()
//Easier to handle due to writing less code
$.get('url or path to file', callbackFunction() )

Working with $.getJSON

$(function() {

function getJSONData() {
  var flickrAPI = '';
  //$.getJSON works specifically to return JSON data from a server
  //Extract specific items from this request by passing an object that contains
  //parameters that will be added on as queries to the link above after the '?'
  //these params are specific to the flickr API
  $.getJSON(flickrAPI, {
    tags: "...",
    tagmode: 'any',
    format: "json"
  }, successFn);
  function successFn(result) { //fullyparsed Javascript function