1.

Did you know that using jQuery's .live() function is more optimal for adding click functions than using .click()? It even handles dynamic content well.
view plain copy to clipboard print ?

01. 02. 03.

$('.clickme').live('click', function() { // Live handler called. });

2.

Attributes in jQuery - jQuery supports passing attributes for an object as the second argument to the jQuery function itself. This creates a new link on the page:
view plain copy to clipboard print ?

01. 02. 03. 04. 05. 06. 07.

$('<a></a>', { text: 'jQuery is awesome!', href: 'http://www.jquery.com', id: 'someAwesomeID', rel: 'external', title: 'This is a title' }).appendTo('body');

3.

Function Grouping - jQuery supports binding functions so that they can all be defined within the same group. This can be useful for keeping your cody tidy among other things!
view plain copy to clipboard print ?

01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11.

jQuery('#foo').bind({ click: function() { // do something }, mouseover: function() { // do something }, mouseout: function() { // do something } })

AddyOsmani.com

1 of 9

4.

Have you ever wanted to convert your JSON string into a JavaScript Object? Rather than having to custom code your own function to do it, just use jQuery's built in .parseJSON function to achieve this easily (jQuery 1.4.1 and above):
view plain copy to clipboard print ?

01. 02. 03. 04. 05. 06. 07.

var obj = jQuery.parseJSON(' {"name":"Larry King", "age": "5000" }'); alert( obj.name === "Larry King" ); //true alert (obj.age === "50");//false alert (obj.age === "5000"); //true

5.

Ever since jQuery 1.4 you've been able to use a jQuery feature equivalent to PHP's sleep() called delay. If you would like to delay and animated effect all you need to do is use delay as follows:
view plain copy to clipboard print ?

01. 02.

$('#myJaw').slideUp(300).delay(800).fadeIn(400);

6.

When styling a large number of elements, instead of using css() it is more efficient to append a style tag to the DOM as follows:
view plain copy to clipboard print ?

01. 02.

$('<style type="text/css"> div.class { color: red; } </style>') .appendTo('head');

7.

Here's how you can remove the parent elements of any object using jQuery's .unwrap() function
view plain copy to clipboard print ?

01. 02. 03. 04. 05.

/* here we locate any paragraph elements and then 'unwrap' the parent elements around them. These could be other divs, spans or anything really */ jQuery('p').unwrap();

AddyOsmani.com

2 of 9

8.

Would you like to perform an action when an element or its contents gain focus? Here's how to do it:
view plain copy to clipboard print ?

01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.

jQuery('form') .focusin(function(){ jQuery(this).addClass('focused'); }); .focusout(function(){ jQuery(this).removeClass('focused'); }); //However, the preferred way to do this is using // .focus() and .blur() //For when an element loses it's focus use .blur() $('#target').blur(function() { alert('Handler for .blur() called.'); }); //For when an element gains focus use .focus() $('#target').focus(function() { alert('Handler for .focus() called.'); });

9.

Each traversal method in jQuery creates a new set which builds a stack. You can use .end() to reach the previous set.
view plain copy to clipboard print ?

01. 02. 03. 04. 05. 06. 07.

$("<ul><li> </li></ul>") // li .find("a") // a .attr("href", "http://www.google.com/") // a .html("Google!") // a .end() // li .appendTo("ul");

10.

I've mentioned this a few times before, but it's a feature that many developers forget exists within jQuery - data() - jQuery actually has an API for invisibly storing data on DOM nodes so you can easily store any information through JS and it'll be available through the same central resource
view plain copy to clipboard print ?

01. 02.

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

11.

Garbage collection of data stored can either be done through removeData() or via the remove() function after the element has been deleted.
view plain copy to clipboard print ?

01. 02. 03. 04.

/* Here are two ways to remove all of the information bound to an element*/ $("div").removeData(); $("div").remove();

AddyOsmani.com

3 of 9

12.

Have you ever tried writing a plugin and run into a problem with overriding specific behaviours?. In jQuery you can override the values set or retrieved on the data method by binding to getData and setData.Returning a value will set/return a totally different result.
view plain copy to clipboard print ?

01. 02. 03. 04.

$("div").bind("getData.value", function() { return myPlugin.realValue; });

13.

jQuery supports namespacing and this includes namespacing data. You can scope your namespaces to a specific name or plugin and this can help you avoid conflicts with other code that might use the same data name.
view plain copy to clipboard print ?

01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14.

/* Why namespace? Namespacing ensures that your variables don't conflict with any others which happen to have the same name. This is important if you want to avoid your code breaking when other files or plugins are included in your page's architecture. See below for an example of namespacing data. */ $("div").data("events.plugin", { //your data here });

14.

Looking for a way to namespace your event handlers?. This sample will show you his. It makes it easier to locate your namespace binding later on and easily remove the handler if needed.
view plain copy to clipboard print ?

01. 02. 03.

$("div").bind("click.plugin", someFn); $("div").bind("focus.plugin", otherFn); $("div").unbind(".plugin");

15.

You can bind to almost any event and there aren't really any limits on what you can or can't bind to.
view plain copy to clipboard print ?

01. 02.

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

AddyOsmani.com

4 of 9

16.

A good tip for complicated applications: Custom events are a useful way for multiple pieces of code to bind to the same functionality, so you trigger one event but lots of handlers can be executed.
view plain copy to clipboard print ?

01. 02. 03.

$("div").bind("remove.pluginA", someFn); $("div").bind("remove.pluginB", otherFn); $("div").trigger("remove");

17.

Have you been trying to find a way to listen to events from a particular context? The delegate and undelegate methods make this possible (supported in jQuery 1.4.2 onwards). There's also a very large performance gain got from switching over to .delegate()!
view plain copy to clipboard print ?

01. 02. 03.

$("table").delegate("td", "hover", function(){ $(this).toggleClass("active"); });

18.

You can dynamically change the context of a function (if needed) using something similar to this. Since jQuery 1.4.* you've also been able to easily remove the proxied function.
view plain copy to clipboard print ?

01. 02. 03.

var obj = { method: function(){} }; $("#foo").click( jQuery.proxy( obj, "method" ) ); $("#foo").unbind( "click", obj.method );

19.

Interested in creating a simple custom selector?. Creating your own selectors is easy and you can do this for your plugins if you would like some easy querying features.
view plain copy to clipboard print ?

01. 02. 03.

jQuery.expr[":"].myplugin = function(elem) { return !!jQuery.data("myplugin"); };

20.

Did you know that you can treat jQuery objects like arrays?. Take a look at this example.
view plain copy to clipboard print ?

01. 02. 03. 04. 05.

/*Here's some sample HTML followed by some jQuery that allows us to access the values of any "box" by index.*/ <div id="wrapper"><div class="box">Content #1!</div> <div class="box">Content #2!</div> </div> <div id="wrapper2"><div class="box">Content2 #1!</div></div>

<div class="box">Content #3!

AddyOsmani.com

5 of 9

view plain

copy to clipboard

print

?

01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16.

// returns 4 $('#wrapper .box').length; // num is equal to 4 var num = $('#wrapper .box'); num = num.length; // text is equal to 'Content #2!' var text = $("#wrapper .box")[1]; // text is equal to 'Content #1' var text = $("#wrapper .box")[0]; // text is equal to 'Content2 #1' var text = $("#wrapper2 .box")[0];

21.

Selection storage: Did you know that you can store the results from a jQuery selection in a variable and *still* have access to the same methods?. Here's a useful example.
view plain copy to clipboard print ?

01. 02. 03. 04.

var $myBox = $('#test'); /*the variable myHTML is equal to the content's of '#test'*/ var myHTML = $myBox.html();

22.

Did you know that jQuery has great support for Callbacks? Here are two ways you can tell if a function has completed running.
view plain copy to clipboard print ?

01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11.

function runAlertNow () { $(this).html('I just ran this function!'); } // both of these lines do the same thing $('#test').slideUp(400, runAlertNow); $('#test').slideUp(400, function () { $(this).html('I just ran the anonymous function!'); });

23.

Very useful tip: Did you know that you can select elements within another element just by passing a second parameter to the jQuery initializer?
view plain copy to clipboard print ?

01.

<div id="yourparent"><div id="mychild"> </div></div>

Here are three ways to access an element within an element:
view plain copy to clipboard print ?

01. 02. 03. 04. 05.

$('#yourparent').find('#mychild') //or even shorter: $('#mychild', $('#yourparent')) //or even shorter: $('#mychild', '#yourparent')

24.

How do you handle access to elements with IDs that contain special characters in jQuery?
view plain copy to clipboard print ?

01. 02.

$("$some[id]").show(); // won't work for this type of ID $("$some\\[id\\]").show() // works fine for the ID: some[id]

AddyOsmani.com

6 of 9

25.

How do you enable or disable form elements within jQuery?
view plain copy to clipboard print ?

01. 02. 03. 04. 05.

//To disable a form element such as a text input field $("#myelement").attr("disabled", "disabled"); //To re‐enable a disabled form element $("#myelement").removeAttr("disabled");

26.

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

01. 02. 03. 04. 05. 06. 07. 08. 09. 10.

/*The .length property in jQuery returns the length or number of elements inside an array or the string length. If you want to check the existence of the element, just check if the returned value of length is zero:*/ if ($(selector).length) { //your code here }

27.

How do you search all the nodes on a page for a particular piece of text using jQuery?
view plain copy to clipboard print ?

01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39.

/*This useful extended function will allow you to pattern match a keyword across all the nodes in a page. See the example below for how GMail use something similar in concept for their search‐keyword highlighting*/ $.fn.egrep = function(pat) { var out = []; var textNodes = function(n) { if (n.nodeType == Node.TEXT_NODE) { var t = typeof pat == 'string' ? n.nodeValue.indexOf(pat) != ‐1 : pat.test(n.nodeValue); if (t) { out.push(n.parentNode); } } else { $.each(n.childNodes, function(a, b) { textNodes(b); }); } }; this.each(function() { textNodes(this); }); return out; }; // Here's an example of using this to highlight //all the nodes on the page that contain the keyword //'jQuery' $("#testbutton").click(function() { var n = $('body').egrep(/jquery/i); for (var i = 0; i < n.length; ++i) { void($(n[i]).css('background', 'yellow')); } });

AddyOsmani.com

7 of 9

28.

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 data associated with the removed elements. This is useful when you want to reinsert removed elements into the DOM later.
view plain copy to clipboard print ?

01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13.

//In the below example $("p").click(function(){ $(this).toggleClass("off"); }); var p; $("button").click(function(){ if ( p ) { p.appendTo("body"); p = null; } else { p = $("p").detach(); } });

29.

You can easily find the closest element to another (beginning at the current element and moving up the DOM) using .closest(). See the below example:
view plain copy to clipboard print ?

01. 02. 03. 04. 05. 06.

$(document).ready(function() { //Let's set the background color of the nearest //UL in this pseudo‐menu $('li.subchild').closest('ul').css('background‐color', 'red'); });
view plain copy to clipboard print ?

01.

<ul>

<li>Parent Menu

<ul>

<li class="subchild">Child Item 1</li>

<li class="subchild">Child Item 2

30.

How to easily and quickly add one-click clearing of default input text values from your fields
view plain copy to clipboard print ?

01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16. 17.

(function($){ $.fn.clearDefault = function(){ return this.each(function(){ var default_value = $(this).val(); $(this).focus(function(){ if ($(this).val() == default_value) $(this).val(""); }); $(this).blur(function(){ if ($(this).val() == "") $(this).val(default_value); }); }); }; })(jQuery); // How to use it: $('input').clearDefault();

AddyOsmani.com

8 of 9

31.

Would you like to style only a particular range of elements within a list? jQuery's .slice() function makes this possible through indices
view plain copy to clipboard print ?

01.

<ul>
view plain

<li>Apples</li>
copy to clipboard

<li>Pears</li>
?

<li>Cherries</li>

<li>Grapes</li>

<li>Mangos</li> </ul>

print

01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11.

/*If we just want to set the background‐color of everything after element number two (pears) we can do this using:*/ $('li').slice(2).css('background‐color', 'yellow'); /*and if we want to set the bg‐color of the elements after two(pears), but only up to and including 4 (grapes), we can use:*/ $('li').slice(2, 4).css('background‐color', 'green')

I hope you found those useful!. - Addy

AddyOsmani.com

9 of 9

Sign up to vote on this title
UsefulNot useful