JQuery

From Code Self Study Wiki
Jump to: navigation, search

This page has notes about jQuery.

jQuery Resources

jQuery Plugins

Selecting and Traversing

Selecting examples:

$("ul");
// all children
$("ul li");
// direct children only
$("ul > li");
$("ul li:first");
$("ul li:last");
$("ul li:odd");
$("ul > li:even");
// multiple selectors
$("#block-5, .author-pic");

Traversing is faster than selecting:

$("#block-4").find("li");

You can use methods instead of filters:

$("ul").first("li");
$("ul").last("li");

Walking the DOM:

$("ul").first("li").next();
$("ul").last("li").prev();
$("ul").first("li").parent();
// limit to direct children
$("#block-4").children("li");

Arrays

each

Loop through array, like to add some list items to an unordered list:

someThings = [ "a", "list", "of", "things", "for", "the", "unordered", "list" ]
$(someThings).each(
  function() {
    $("ul").append("<li>" + this + "</li>"); // the <ul></ul> should be on the page somewhere
  }
);

TODO: difference between jQuery's each and JavaScript's forEach.

Getters and Setters

Pass the method a value and it sets it. Leave it blank and it gets it.

HTML

attr and removeAttr

The attr method sets all the matching elements but gets only the first value in a set. See also map.

Here are some examples:

  // get the value of the class on the first <ul> on the page
  x = $("ul").attr("class");
  // add target="_blank" to each link on a page
  $("a").attr("target", "_blank");
  // remove target="_blank"
  $("a").removeAttr("target");

CSS

Examples:

  // get info about the CSS
  $("p").css("fontSize");
  // set some CSS
  $("p").css("font-size", "20px"); // can also use camelCase
  // style all links on a page using camelCase and an object
  $("a").css({ backgroundColor: "blue",
               color: "white" });
  // apply a new style
  $("p").addClass("test-style");
  // remove a style
  $("p").removeClass("test-style");

You can also toggleClass.

Forms

val

// get the value of an input field by its ID
x = $("#firstname").val();
// set the value of an input field by its ID
$("#firstname").val("George");

text and html

// get the old title
x = $("head title").text();
// set a new title
$("head title").text("New title " + x)
// get the contents
$("#intro").html();
// inster some text
$("#intro").html("Some new text");

data and removeData

Doesn't work with <applet>, <embed>, and <object>.

// assign some data
$("#testid").data("x", 5);
 
// retrieve the data
$("#testid").data("x");
 
// remove it
$("#testid").removeData("x");

AJAX / XHR

From Evan's presentation:

$('#myButton').click(function () {
    var a, b, c;
    $.getJSON('json/a.json').then(function (x) {
        a = x;
        return $.getJSON('json/b.json');
    }).then(function (x) {
        b = x;
        return $.getJSON('json/c.json');
    }).then(function (x) {
        c = x;
        alertJSON([a, b, c]); 
    });
});

Interesting way to run through URLs and fetch them with promises:

$('#myButton').click(function () {
    var ps = _.map(urls, getDiyPromise);
    DiyPromise.all(ps).then(alertJSON);
});

Changing Document Structure

$(target).method(content)

  • append and prepend add things to the beginning or end of an element
  • before and after add things before or after the element tags.
  • replaceWith

This example is from JavaScript: The Definitive Guide:

// replace the <h2>s with <h1>s while keeping the content
$("h2").each(function() {
  var h2 = $(this);
  h2.replaceWith("<h1>" + h2.html() + "</h1>");
});

$(content).method(target)

These variations work in the other direction:

  • appendTo and prependTo
  • insertBefore and insertAfter
  • replaceAll
// put a <br> before <p> elements
$("<br>").insertBefore("p");

clone()

Copy elements instead of moving them.

wrap()

  • wrap() -- puts a new element around the existing tags
  • wrapInner -- puts a new element inside the existing tags
  • wrapAll() -- wrap all but the specified tag (may also group them?)

Example:

// wrap a span around all <i> elements
$("i").wrap('<span class="highlight"></span>');

Deleting Elements

  • empty()
  • delete()
  • remove()
  • detach()
  • unwrap()

Events

Since jQuery 1.7, I think you're supposed to use .on() instead of these directly. So, .click() becomes something like:

function notify() { alert("clicked"); }
$("button").on("click", notify);
  • blur()
  • change()
  • click()
  • dblclick()
  • error()
  • focus()
  • focusin()
  • focusout()
  • keydown()
  • keypress()
  • keyup()
  • load()
  • mousedown()
  • mouseenter()
  • mouseleave()
  • mousemove()
  • mouseout()
  • mouseover()
  • mouseup()
  • resize()
  • scroll()
  • select()
  • submit()
  • unload()

bind()

Use .on() instead of .bind(), but it appears in older code.

.bind( eventType [, eventData ], handler(eventObject) )

Here is an example from the docs:[1]

$('#foo').bind({
  click: function() {
    // do something on click
  },
  mouseenter: function() {
    // do something on mouseenter
  }
});

Undo it with .unbind().

Snippets

Animated Scroll to Anchor

$("a[href^=#]").click(function () {
    $("html, body").animate({
        scrollTop: $($(this).attr("href")).offset().top
    }, 1000);
    return false;
});

References

  1. http://api.jquery.com/bind/