jQuery

OBJECTIVES

In this unit, the student will learn:
  • How to incorporate jQuery in a web page
  • jQuery syntax
    • jQuery selectors
    • jQuery objects
    • Creating elements with jQuery
  • jQuery DOM methods
    • Content manipulation
    • CSS and class manipulation
    • Handling events
    • DOM traversal (skim)
    • jQuery effects (skim)

What is jQuery?

  • A library for JavaScript
  • Simplifies JavaScript programming
    • DOM modification and traversal
      • Never have to type document.getElementById again!
    • CSS manipulation
    • Event handling
    • Effects and animations
    • Ajax
  • Provides cross-browser compatibility

Alternatives to jQuery

  • The Stepp et al textbook does not cover jQuery. It uses (Chapter 10 ff):
  • There are many more frameworks out there.
    • For more information, see W3Schools JavaScript Libraries page.
    • jQuery seems to be prevailing in the market, so I chose it.
    • If you are planning a big project, research the differences carefully.

Getting jQuery

jQuery is free. You can:
  • Download the jQuery library from jQuery.com
    • Put it in a suitable directory
    • Then add a <script> element to your page to include it
      • If you do this, do not add your own code to it: use a separate file.
  • Include jQuery from a CDN (Content Delivery Network)
    • Google and Microsoft provide it
    • The <script> element points directly to the provider
Using a CDN is preferable.
  • File will be fetched from nearest server
  • Since other sites use same CDN, browser may have it cached

jQuery versions

  • Latest jQuery versions are 1.11.2 and 2.1.3
  • jQuery.com says:
    • “jQuery 2.x has the same API as jQuery 1.x, but does not support Internet Explorer 6, 7, or 8... Since IE 8 is still relatively common, we recommend using the 1.x version unless you are certain no IE 6/7/8 users are visiting the site.”
  • Version 2.1.3 is only about 10% smaller than 1.11.2 (minified)
    • I agree with their recommendation

jQuery formats

The jQuery library is available in 2 formats:
  • Development version jquery-1.11.2.js
    • Human readable, commented, but larger size file (280 kB)
    • Read it and learn stuff
  • Minified version jquery-1.11.2.min.js
    • Smaller size file (96 kB)
    • Variables renamed to a, b, etc.
    • No comments, no unnecessary whitespace
    • Use it for your pages but don't try to read it

jQuery syntax

  • Basically all jQuery statements are of this form:
    • $(something).method(...)
    • or jQuery(something).method(...)
      • use synonym jQuery to avoid conflicts if using other libraries that define a $ function (see noConflict)
  • The something may be almost anything: CSS selector, HTML snippet, object...
    • The jQuery routines figure out what to do based on the kind of argument
  • The method is the operation to perform
Example:
$("#goButton").hide(); — hides element with id="goButton"

The $(document).ready function

$(document).ready( function() {
  statements
});
This is like the DOM construction:
window.onload = function() {
  statements
};
but runs earlier (does not wait for images etc. to download).
  • Waits till document has been created, so elements in it exist
  • As a convenience, there is this less readable shorthand:
    $( function() { statements } );

Do we need $(document).ready?

  • Why not just place the <script> tags at the end of the body?
    • That way, all DOM elements are guaranteed to be loaded
    • In fact, you will see many sites that do this
  • Placing scripts in the head has disadvantages
    • Browser has to fetch the scripts and execute them before proceeding with parsing and rendering HTML
      • because they may put content into page with document.write (rarely true nowadays)
    • This waiting slows down page load
  • But placing them at the end is bad too
    • Browser must wait till parsing is done before downloading scripts
    • Page not live till all scripts are downloaded and run
    • Better to download them asynchronously while parsing continues

The modern solution

  • Put <script> tags in head, do use $(document).ready
  • Use HTML5 async or defer attributes
    • Supported by most current browsers
    • No harm done if browser does not support them
  • <script src="mycode.js" async></script>
    • Browser will load script asynchronously
    • Script is executed as soon as loaded
  • <script src="mycode.js" defer></script>
    • Browser will load script asynchronously
    • Multiple scripts will be run in order of occurrence
      • Use this with jQuery or you will get "$ undefined" error
See more elaborate discussion here.

jQuery selectors

  • Any CSS selector (in quotes) can go inside $( ... )
    • like DOM method querySelectorAll
    • But no worries about arrayness: automatically applies method to all
Examples:
$("p").hide() — hides all paragraph elements.
$(".info").show() — unhides all elements with class="info".
$("#info").text("message") — sets text of element with id="info".
$("div > p").css("border", "1px solid gray"); — applies border to all paragraphs that are children of a div.
Complete list at api.jquery.com/category/selectors/.

DOM contextual search

  • DOM methods allow you to search within children of an element
    • Example: suppose you want to search for list elements with class="foo" that are children of a specific ul with id="bar"
DOM picture
DOM way:
var ul = document.getElementById("bar");
var a = ul.querySelectorAll("li.foo");

Result: a is array of desired elements.

jQuery way:
var ul = $("#bar");
var a = $("li.foo",ul);
 Example  Code

Acknowledgement: figure taken from Stepp et al companion site jQuery slides

The jQuery object

  • The $ function always returns an array-like object
  • The selected elements are items in the array
  • Not the same array as returned by corresponding DOM methods
Thus:
document.getElementById("myid") != $("#myid")
document.getElementById("myid") == $("#myid")[0]

document.getElementsByTagName("p") != $("p")
document.getElementsByTagName("p")[0] == $("p")[0]

jQuery with objects

  • An object can go inside $( ... ), e.g.
    • $(document) — the document object
    • $(this) — the object that fired an event
    • $(myobj) — a user-defined object
      • Note: no quotes!
  • This gives it the “jQuery upgrade”
    • Extra functionality
    • But beware: it is now a “jQuery object”
    • The original object is its first element
      • Use $(object)[0] to get at native properties if needed

Creating new elements

  • Create a new element by $("<tag>")
    • Or $("<tag></tag>") if you prefer
Example:
$("<div>").text("Here's a new div!").appendTo("body");
  • This example also illustrates chaining: applying a method to the result of a previous method.
    • a very common jQuery motif
  • Actually any HTML snippet (starting with "<") can be given, e.g.
    • $("<div>Here's a <b>new</b> div!</div>").appendTo("body");
    • I don't recommend using this for complex HTML, it's error prone.

jQuery DOM content methods

Methods to query and modify document content.
  • Get methods:
    • $(elem).text() — returns text content of element(s)
    • $(elem).html() — returns HTML content including tags
    • $(elem).val() — returns value of form field
      • If more than one match, text returns combined content, html and val use first match
  • Set methods:
    • $(elem).text("string") — sets text content of element(s)
    • $(elem).html("string") — sets HTML content
    • $(elem).val("string") — sets value of form field

Setting content with a callback

The set methods can be passed a function as argument, called a callback.
  • This function will be invoked for each of the selected elements.
  • It receives two arguments:
    1. index of element in list of selected elements
    2. original value being replaced
  • The return value of the function is used as the content
Example (live)  HTML  JS Code

Get/set attributes

  • $(elem).attr(attr-name) — returns value of given attribute for first matching element
  • $(elem).attr(attr-name,attr-value) — sets value of given attribute
    • Can also use a callback as second argument
Example (live)  HTML & JS

Get/set properties

  • $(elem).prop(prop-name) — returns value of given property for first matching element
  • $(elem).prop(prop-name,prop-value) — sets value of given property
    • Can also use a callback as second argument
Properties and attributes are different things. See api.jquery.com/prop/.
  • For example menu selectedIndex is a property, not an attribute.
  • For a checkbox,
    • .prop("checked") is checked state, changes when box is clicked
    • .attr("checked") is initial state (checked attribute present), does not change when box is clicked
Example   HTML   JS Code

Adding DOM elements

  • $(selector).append(content) — inserts content at the end of the selected element(s)
  • $(selector).prepend(content) — inserts content at the front of the selected element(s)
  • These insert the new content as a child element
    • Each method can take multiple arguments, creating multiple child elements
Example: $("p").append("Hello"); — appends the text “Hello” to the end of all paragraphs.

Adding DOM elements

  • $(selector).after(content) — inserts content after the selected element(s)
  • $(selector).before(content) — inserts content before the selected element(s)
  • These insert the new content as a sibling element
    • Each method can take multiple arguments, creating multiple sibling elements
Example: $("div").after("<p>Hello</p>"); — adds a paragraph with the text “Hello” following each div.

Alternative methods

  • $(content).appendTo(selector)
  • $(content).prependTo(selector)
  • $(content).insertBefore(selector)
  • $(content).insertAfter(selector)
These perform same tasks as the methods on previous slides, but the syntax is reversed: content first, destination second.
  • The content can be a selector; this moves selected element(s) of page to new location.
    • If destination selector matches more than one element, copies of content will be made for the extra destinations.

Removing elements

  • $(selector).remove() — remove the selected element(s) and its child elements
  • $(selector).remove(filter) — remove the selected element(s) matching the filter (another selector)
  • $(selector).empty() — remove all children of the selected element(s)
Example: equivalent ways to remove div(s) with class="junk":
$("div.junk").remove();
$("div").remove(".junk");

Manipulating CSS properties

  • $(selector).css("property") — get value of CSS property
  • $(selector).css("property","value") — set value of CSS property
    • Second argument can be a callback function with arguments of index and old CSS property value
  • $(selector).css({"property":"value","property":"value",...})
    • Reminder: the {"name":"value","name":"value",...} construct is a standard JavaScript object (JSON) literal.
    • For property names, jQuery understands both DOM (unquoted) and CSS (quoted) forms, e.g.:
      $("body").css({color:"white",backgroundColor:"green"}) or
      $("body").css({"color":"white","background-color":"green"})
Of course, the notions of unobtrusive CSS apply to jQuery too. Preferably work with classes instead.

Manipulating classes

  • $(selector).addClass(class-name) — add class(es) to selected element(s)
  • $(selector).removeClass(class-name) — remove class(es) from selected element(s)
  • $(selector).toggleClass(class-name) — toggle class(es) for selected element(s): add if not present, remove if present
  • $(selector).toggleClass(class-name,addOrRemove) — if boolean addOrRemove is true, add class, if false remove
  • Example: use chaining to replace one class by another for an element:
    $("#feedback").removeClass("low").addClass("high");
    • For each method, to add/remove/toggle multiple classes at once, supply space-separated list.
    (Repeated) Example  HTML  jQuery Code

jQuery event methods

  • Commonly used events have their own methods to assign handlers:
    • Mouse button: click(), dblclick()
    • Mouse motion: mouseenter(), mouseleave()
    • Keyboard: keypress(), keydown(), keyup()
    • Form: submit(), change(), focus(), blur()
      • focus and blur fire when form field gets or loses keyboard focus
    • Document/Window: load(), resize(), scroll(), unload()
      • $(window).unload() fires when browser is about to leave page
  • All of these take a function as argument, attach it as event handler
See complete list at http://api.jquery.com/category/events/.

The on() function

  • All of the methods on previous page are shortcuts for
    $(elem).on("event",handler);
    • Like DOM addEventListener("event",handler);
    • But compatible with browsers that don't support that (like IE 8)
    Example (live)  HTML  JS Code
  • But this function has other forms, including:
    $(elem).on({"event":handler,"event":handler,...});
    • Assigns handlers to multiple events
    Example (live)  HTML  JS Code

Removing event handlers

  • Events attached with on() can be removed with off()
    $(elem).off("event",handler);
    • Like DOM removeEventListener("event",handler);
  • Or:
    $(elem).off({"event":handler,"event":handler,...});
    • Remove handlers from multiple events

DOM traversal in jQuery

  • jQuery provides many methods for traversing the DOM:
    • Ancestor/descendant: parent(), parents(), children(), find()
    • Siblings: siblings(), next(), nextAll(), prev(), prevAll()
  • We will not look at these in detail.
See complete list and descriptions at http://api.jquery.com/category/traversing/.

The each() function

  • $(selector).each( function )
    • Applies function to each selected element
    • Function receives two arguments:
      1. index of element in list of selected elements
      2. the current element as plain DOM object
        • ($(this) jQuery object also available)
    • Note that jQuery methods already iterate over all selected elements.
      • a.each( function(){ $(this).css("color","blue"); } ); is equivalent to:
        a.css( "color","blue" );
      • Use each() when you need to do something you can't do by a jQuery method

Effects

  • jQuery has several methods for visual effects:
    • hiding/showing elements
    • animation
    • fade in, fade out, slide up or down
  • We will look only at two: hide(), show().
More at http://api.jquery.com/category/effects/.

Hiding and showing elements

  • Hide element(s) with $(elem).hide()
    • Same effect as setting CSS display to none
    • But remembers previous value (e.g. inline or block)
  • Display previously hidden element(s) with $(elem).show()
    • Restores previous display value