31 jQuery Snippets That Will Help Make You a JavaScript Pro

download 31 jQuery Snippets That Will Help Make You a JavaScript Pro

of 9

Transcript of 31 jQuery Snippets That Will Help Make You a JavaScript Pro

  • 8/9/2019 31 jQuery Snippets That Will Help Make You a JavaScript Pro

    1/9

    Did you know that using jQuery's .live() function is moreoptimal for adding click functions than using .click()? It evenhandles dynamic content well.

    view plain copy to clipboard print ?

    $('.clickme').live('click', function() {01.

    // Live handler called.02.

    });03.

    1.

    Attributes in jQuery - jQuery supports passing attributes for anobject as the second argument to the jQuery function itself. Thiscreates a new link on the page:

    view plain copy to clipboard print ?

    $('', {01.

    text: 'jQuery is awesome!',02.

    href: 'http://www.jquery.com',03.

    id: 'someAwesomeID',04.

    rel: 'external',05.

    title: 'This is a title'06.

    }).appendTo('body');07.

    2.

    Function Grouping - jQuery supports binding functions so thatthey can all be defined within the same group. This can be usefulfor keeping your cody tidy among other things!

    view plain copy to clipboard print ?

    jQuery('#foo').bind({01.

    click: function() {02.

    // do something03.

    },04.

    mouseover: function() {05.

    // do something06.

    },07.

    mouseout: function() {08.

    // do something09.

    }10.

    })11.

    3.

    yOsmani.com 1 of 9

  • 8/9/2019 31 jQuery Snippets That Will Help Make You a JavaScript Pro

    2/9

  • 8/9/2019 31 jQuery Snippets That Will Help Make You a JavaScript Pro

    3/9

    Would you like to perform an action when an element or itscontents gain focus? Here's how to do it:

    view plain copy to clipboard print ?

    jQuery('form')01.

    .focusin(function(){02.

    jQuery(this).addClass('focused');03.

    });04.

    .focusout(function(){05.

    jQuery(this).removeClass('focused');06.

    });07.

    08.

    //However, the preferred way to do this is using09.

    // .focus() and .blur()10.

    11.

    //For when an element loses it's focus use .blur()12.

    $('#target').blur(function() {13.

    alert('Handler for .blur() called.');14.

    });15.

    16.

    //For when an element gains focus use .focus()17.

    $('#target').focus(function() {18.

    alert('Handler for .focus() called.');19.

    });20.

    8.

    Each traversal method in jQuery creates a new set which builds astack. You can use .end() to reach the previous set.

    view plain copy to clipboard print ?

    $(" ") // li01.

    .find("a") // a02.

    .attr("href", "http://www.google.com/") // a03.

    .html("Google!") // a04.

    .end() // li05.

    .appendTo("ul");06.

    07.

    9.

    I've mentioned this a few times before, but it's a feature thatmany developers forget exists within jQuery - data() - jQueryactually has an API for invisibly storing data on DOM nodes soyou can easily store any information through JS and it'll beavailable through the same central resource

    view plain copy to clipboard print ?

    $("div").data("myName", 'addy');01.

    $("div").data("myName") === 'addy';02.

    10.

    Garbage collection of data stored can either be done throughremoveData() or via the remove() function after the element hasbeen deleted.

    view plain copy to clipboard print ?

    /* Here are two ways to remove all of the information01.

    bound to an element*/02.

    $("div").removeData();03.

    $("div").remove();04.

    11.

    yOsmani.com 3 of 9

  • 8/9/2019 31 jQuery Snippets That Will Help Make You a JavaScript Pro

    4/9

    Have you ever tried writing a plugin and run into a problemwith overriding specific behaviours?. In jQuery you can overridethe values set or retrieved on the data method by binding to

    getData and setData.Returning a value will set/return a totallydifferent result.

    view plain copy to clipboard print ?

    $("div").bind("getData.value", function()01.

    {02.

    return myPlugin.realValue;03.

    });04.

    12.

    jQuery supports namespacing and this includes namespacing

    data. You can scope your namespaces to a specific name orplugin and this can help you avoid conflicts with other code thatmight use the same data name.

    view plain copy to clipboard print ?

    /*01.

    Why namespace? Namespacing ensures that your02.

    variables don't conflict with any others which03.

    happen to have the same name. This is important04.

    if you want to avoid your code breaking when05.

    other files or plugins are included in your06.

    page's architecture. See below for an example of07.

    namespacing data.08.

    */09.

    10.$("div").data("events.plugin",11.

    {12.

    //your data here13.

    });14.

    13.

    Looking for a way to namespace your event handlers?. Thissample will show you his. It makes it easier to locate yournamespace binding later on and easily remove the handler ifneeded.

    view plain copy to clipboard print ?

    $("div").bind("click.plugin", someFn);01.

    $("div").bind("focus.plugin", otherFn);02.

    $("div").unbind(".plugin");03.

    14.

    You can bind to almost any event and there aren't really anylimits on what you can or can't bind to.

    view plain copy to clipboard print ?

    $("div").bind("myplugin", someFn);01.

    $("div").trigger("myplugin");02.

    15.

    yOsmani.com 4 of 9

  • 8/9/2019 31 jQuery Snippets That Will Help Make You a JavaScript Pro

    5/9

    A good tip for complicated applications: Custom events are auseful way for multiple pieces of code to bind to the samefunctionality, so you trigger one event but lots of handlers canbe executed.

    view plain copy to clipboard print ?

    $("div").bind("remove.pluginA", someFn);01.

    $("div").bind("remove.pluginB", otherFn);02.

    $("div").trigger("remove");03.

    16.

    Have you been trying to find a way to listen to events from aparticular context? The delegate and undelegate methods makethis possible (supported in jQuery 1.4.2 onwards). There's also avery large performance gain got from switching over to.delegate()!

    view plain copy to clipboard print ?

    $("table").delegate("td", "hover", function(){01.

    $(this).toggleClass("active");02.

    });03.

    17.

    You can dynamically change the context of a function (if needed)using something similar to this. Since jQuery 1.4.* you've alsobeen able to easily remove the proxied function.

    view plain copy to clipboard print ?

    var obj = { method: function(){} };01.

    $("#foo").click( jQuery.proxy( obj, "method" ) );02.

    $("#foo").unbind( "click", obj.method );03.

    18.

    Interested in creating a simple custom selector?. Creating yourown selectors is easy and you can do this for your plugins if youwould like some easy querying features.

    view plain copy to clipboard print ?

    jQuery.expr[":"].myplugin = function(elem) {01.

    return !!jQuery.data("myplugin");02. };03.

    19.

    Did you know that you can treat jQuery objects like arrays?.Take a look at this example.

    view plain copy to clipboard print ?

    /*Here's some sample HTML followed by some jQuery01.

    that allows us to access the values of any "box"02.

    by index.*/03.

    Content #1! Content #2!

    04.

    Content2 #1!05.

    20.

    yOsmani.com 5 of 9

  • 8/9/2019 31 jQuery Snippets That Will Help Make You a JavaScript Pro

    6/9

    view plain copy to clipboard print ?

    01.

    // returns 402.

    $('#wrapper .box').length;03.

    04.

    // num is equal to 405.

    var num = $('#wrapper .box');06.

    num = num.length;07.

    08.

    // text is equal to 'Content #2!'09.

    var text = $("#wrapper .box")[1];10.

    11.// text is equal to 'Content #1'12.

    var text = $("#wrapper .box")[0];13.

    14.

    // text is equal to 'Content2 #1'15.

    var text = $("#wrapper2 .box")[0];16.

    Selection storage: Did you know that you can store the resultsfrom a jQuery selection in a variable and *still* have access tothe same methods?. Here's a useful example.

    view plain copy to clipboard print ?

    var $myBox = $('#test');01.

    /*the variable myHTML is equal to the content's of02.

    '#test'*/03.

    var myHTML = $myBox.html();04.

    21.

    Did you know that jQuery has great support for Callbacks? Hereare two ways you can tell if a function has completed running.

    view plain copy to clipboard print ?

    function runAlertNow ()01.

    {02.

    $(this).html('I just ran this function!');03.

    }04.

    05.

    // both of these lines do the same thing06.$('#test').slideUp(400, runAlertNow);07.

    $('#test').slideUp(400, function ()08.

    {09.

    $(this).html('I just ran the anonymous function!');10.

    });11.

    22.

    Very useful tip: Did you know that you can select elementswithin another element just by passing a second parameter tothe jQuery initializer?

    view plain copy to clipboard print ?

    01.

    23.

    Here are three ways to access an element within an element:

    view plain copy to clipboard print ?

    $('#yourparent').find('#mychild')01.

    //or even shorter:02.

    $('#mychild', $('#yourparent'))03.

    //or even shorter:04.

    $('#mychild', '#yourparent')05.

    How do you handle access to elements with IDs that containspecial characters in jQuery?

    view plain copy to clipboard print ?

    $("$some[id]").show(); // won't work for this type of ID01.

    $("$some\\[id\\]").show() // works fine for the ID: some[id]02.

    24.

    yOsmani.com 6 of 9

  • 8/9/2019 31 jQuery Snippets That Will Help Make You a JavaScript Pro

    7/9

    How do you enable or disable form elements within jQuery?

    view plain copy to clipboard print ?

    //To disable a form element such as a text input field01.

    $("#myelement").attr("disabled", "disabled");02.

    03.

    //To reenable a disabled form element04.

    $("#myelement").removeAttr("disabled");05.

    25.

    How do you check if something exists in the DOM using jQuery:view plain copy to clipboard print ?

    /*The .length property in jQuery returns the length01.

    or number of elements inside an array or the string02.

    length. If you want to check the existence of the03.

    element, just check if the returned value of length04.

    is zero:*/05.

    06.

    if ($(selector).length)07.

    {08.

    //your code here09.

    }10.

    26.

    How do you search all the nodes on a page for a particular pieceof text using jQuery?

    view plain copy to clipboard print ?

    /*This useful extended function will allow you to01.

    pattern match a keyword across all the nodes in a02.

    page. See the example below for how GMail use something03.

    similar in concept for their searchkeyword highlighting*/04.

    05.

    $.fn.egrep = function(pat) {06.

    var out = [];07.

    var textNodes = function(n) {08.

    if (n.nodeType == Node.TEXT_NODE) {09.

    var t = typeof pat == 'string' ?10.

    n.nodeValue.indexOf(pat) != 1 :11.pat.test(n.nodeValue);12.

    if (t) {13.

    out.push(n.parentNode);14.

    }15.

    }16.

    else {17.

    $.each(n.childNodes, function(a, b) {18.

    textNodes(b);19.

    });20.

    }21.

    };22.

    this.each(function() {23.

    textNodes(this);24.

    });25.

    return out;26.

    };27.

    28.// Here's an example of using this to highlight29.

    //all the nodes on the page that contain the keyword30.

    //'jQuery'31.

    $("#testbutton").click(function()32.

    {33.

    var n = $('body').egrep(/jquery/i);34.

    for (var i = 0; i < n.length; ++i)35.

    {36.

    void($(n[i]).css('background', 'yellow'));37.

    }38.

    });39.

    27.

    yOsmani.com 7 of 9

  • 8/9/2019 31 jQuery Snippets That Will Help Make You a JavaScript Pro

    8/9

    Have you ever wanted to retain any of the information.remove() strips from the DOM? The .detach() method is a lot

    like remove() except that .detach() keeps all jQuery dataassociated with the removed elements. This is useful when youwant to reinsert removed elements into the DOM later.

    view plain copy to clipboard print ?

    //In the below example01.

    $("p").click(function(){02.

    $(this).toggleClass("off");03.

    });04.

    var p;05.

    $("button").click(function(){06.

    if ( p ) {07.

    p.appendTo("body");08.

    p = null;09.} else {10.

    p = $("p").detach();11.

    }12.

    });13.

    28.

    You can easily find the closest element to another (beginning atthe current element and moving up the DOM) using .closest().See the below example:

    view plain copy to clipboard print ?

    $(document).ready(function()01.

    {02.

    //Let's set the background color of the nearest03.

    //UL in this pseudomenu04.

    $('li.subchild').closest('ul').css('backgroundcolor', 'red');05.

    });06.

    view plain copy to clipboard print ?

    Parent Menu Child Item 1 Child01.

    29.

    How to easily and quickly add one-click clearing of default inputtext values from your fields

    view plain copy to clipboard print ?

    (function($){01.

    $.fn.clearDefault = function(){02.

    returnthis.each(function(){03.

    var default_value = $(this).val();04.

    $(this).focus(function(){05.

    if ($(this).val() == default_value)06.

    $(this).val("");07.

    });08.

    $(this).blur(function(){09.

    if ($(this).val() == "")10.

    $(this).val(default_value);11.

    });12.

    });13.

    };14.

    })(jQuery);15.16.

    // How to use it: $('input').clearDefault();17.

    30.

    yOsmani.com 8 of 9

  • 8/9/2019 31 jQuery Snippets That Will Help Make You a JavaScript Pro

    9/9

    Would you like to style only a particular range of elementswithin a list? jQuery's .slice() function makes this possible

    through indicesview plain copy to clipboard print ?

    Apples Pears Cherries Grapes Mangos01.

    view plain copy to clipboard print ?

    /*If we just want to set the backgroundcolor of01.

    everything after element number two (pears) we02.

    can do this using:*/03.

    04.

    $('li').slice(2).css('backgroundcolor', 'yellow');05.

    06.

    /*and if we want to set the bgcolor of the elements07.

    after two(pears), but only up to and including 408.

    (grapes), we can use:*/09.$('li').slice(2, 4).css('backgroundcolor', 'green')10.

    11.

    31.

    I hope you found those useful!.

    - Addy