You are on page 1of 9

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. $('.clickme').live('click', function() {


02. // Live handler called.
03. });

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. $('<a></a>', {
02. text: 'jQuery is awesome!',
03. href: 'http://www.jquery.com',
04. id: 'someAwesomeID',
05. rel: 'external',
06. title: 'This is a title'
07. }).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. jQuery('#foo').bind({
02. click: function() {
03. // do something
04. },
05. mouseover: function() {
06. // do something
07. },
08. mouseout: function() {
09. // do something
10. }
11. })

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. var obj = jQuery.parseJSON('


02. {"name":"Larry King",
03. "age": "5000"
04. }');
05. alert( obj.name === "Larry King" ); //true
06. alert (obj.age === "50");//false
07. 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. $('#myJaw').slideUp(300).delay(800).fadeIn(400);
02.

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. $('<style type="text/css"> div.class { color: red; } </style>')


02. .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. /* here we locate any paragraph elements and then


02. 'unwrap' the parent elements around them. These
03. could be other divs, spans or anything really */
04.
05. 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. jQuery('form')
02. .focusin(function(){
03. jQuery(this).addClass('focused');
04. });
05. .focusout(function(){
06. jQuery(this).removeClass('focused');
07. });
08.
09. //However, the preferred way to do this is using
10. // .focus() and .blur()
11.
12. //For when an element loses it's focus use .blur()
13. $('#target').blur(function() {
14. alert('Handler for .blur() called.');
15. });
16.
17. //For when an element gains focus use .focus()
18. $('#target').focus(function() {
19. alert('Handler for .focus() called.');
20. });

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. $("<ul><li> </li></ul>") // li


02. .find("a") // a
03. .attr("href", "http://www.google.com/") // a
04. .html("Google!") // a
05. .end() // li
06. .appendTo("ul");
07.

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. $("div").data("myName", 'addy');


02. $("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. /* Here are two ways to remove all of the information


02. bound to an element*/
03. $("div").removeData();
04. $("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. $("div").bind("getData.value", function()


02. {
03. return myPlugin.realValue;
04. });

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. Why namespace? Namespacing ensures that your
03. variables don't conflict with any others which
04. happen to have the same name. This is important
05. if you want to avoid your code breaking when
06. other files or plugins are included in your
07. page's architecture. See below for an example of
08. namespacing data.
09. */
10.
11. $("div").data("events.plugin",
12. {
13. //your data here
14. });

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. $("div").bind("click.plugin", someFn);


02. $("div").bind("focus.plugin", otherFn);
03. $("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. $("div").bind("myplugin", someFn);


02. $("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. $("div").bind("remove.pluginA", someFn);


02. $("div").bind("remove.pluginB", otherFn);
03. $("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. $("table").delegate("td", "hover", function(){


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

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. var obj = { method: function(){} };


02. $("#foo").click( jQuery.proxy( obj, "method" ) );
03. $("#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. jQuery.expr[":"].myplugin = function(elem) {


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

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. /*Here's some sample HTML followed by some jQuery


02. that allows us to access the values of any "box"
03. by index.*/
04. <div id="wrapper"><div class="box">Content #1!</div> <div class="box">Content #2!</div> <div class="box">Content #3!
</div>
05. <div id="wrapper2"><div class="box">Content2 #1!</div></div>

AddyOsmani.com 5 of 9
view plain copy to clipboard print ?

01.
02. // returns 4
03. $('#wrapper .box').length;
04.
05. // num is equal to 4
06. var num = $('#wrapper .box');
07. num = num.length;
08.
09. // text is equal to 'Content #2!'
10. var text = $("#wrapper .box")[1];
11.
12. // text is equal to 'Content #1'
13. var text = $("#wrapper .box")[0];
14.
15. // text is equal to 'Content2 #1'
16. 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. var $myBox = $('#test');


02. /*the variable myHTML is equal to the content's of
03. '#test'*/
04. 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. function runAlertNow ()


02. {
03. $(this).html('I just ran this function!');
04. }
05.
06. // both of these lines do the same thing
07. $('#test').slideUp(400, runAlertNow);
08. $('#test').slideUp(400, function ()
09. {
10. $(this).html('I just ran the anonymous function!');
11. });

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. $('#yourparent').find('#mychild')
02. //or even shorter:
03. $('#mychild', $('#yourparent'))
04. //or even shorter:
05. $('#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. $("$some[id]").show(); // won't work for this type of ID


02. $("$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. //To disable a form element such as a text input field


02. $("#myelement").attr("disabled", "disabled");
03.
04. //To re‐enable a disabled form element
05. $("#myelement").removeAttr("disabled");

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

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


02. or number of elements inside an array or the string
03. length. If you want to check the existence of the
04. element, just check if the returned value of length
05. is zero:*/
06.
07. if ($(selector).length)
08. {
09. //your code here
10. }

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. /*This useful extended function will allow you to


02. pattern match a keyword across all the nodes in a
03. page. See the example below for how GMail use something
04. similar in concept for their search‐keyword highlighting*/
05.
06. $.fn.egrep = function(pat) {
07. var out = [];
08. var textNodes = function(n) {
09. if (n.nodeType == Node.TEXT_NODE) {
10. var t = typeof pat == 'string' ?
11. n.nodeValue.indexOf(pat) != ‐1 :
12. pat.test(n.nodeValue);
13. if (t) {
14. out.push(n.parentNode);
15. }
16. }
17. else {
18. $.each(n.childNodes, function(a, b) {
19. textNodes(b);
20. });
21. }
22. };
23. this.each(function() {
24. textNodes(this);
25. });
26. return out;
27. };
28.
29. // Here's an example of using this to highlight
30. //all the nodes on the page that contain the keyword
31. //'jQuery'
32. $("#testbutton").click(function()
33. {
34. var n = $('body').egrep(/jquery/i);
35. for (var i = 0; i < n.length; ++i)
36. {
37. void($(n[i]).css('background', 'yellow'));
38. }
39. });

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. //In the below example


02. $("p").click(function(){
03. $(this).toggleClass("off");
04. });
05. var p;
06. $("button").click(function(){
07. if ( p ) {
08. p.appendTo("body");
09. p = null;
10. } else {
11. p = $("p").detach();
12. }
13. });

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. $(document).ready(function()
02. {
03. //Let's set the background color of the nearest
04. //UL in this pseudo‐menu
05. $('li.subchild').closest('ul').css('background‐color', 'red');
06. });

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. (function($){
02. $.fn.clearDefault = function(){
03. return this.each(function(){
04. var default_value = $(this).val();
05. $(this).focus(function(){
06. if ($(this).val() == default_value)
07. $(this).val("");
08. });
09. $(this).blur(function(){
10. if ($(this).val() == "")
11. $(this).val(default_value);
12. });
13. });
14. };
15. })(jQuery);
16.
17. // 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> <li>Apples</li> <li>Pears</li> <li>Cherries</li> <li>Grapes</li> <li>Mangos</li> </ul>

view plain copy to clipboard print ?

01. /*If we just want to set the background‐color of


02. everything after element number two (pears) we
03. can do this using:*/
04.
05. $('li').slice(2).css('background‐color', 'yellow');
06.
07. /*and if we want to set the bg‐color of the elements
08. after two(pears), but only up to and including 4
09. (grapes), we can use:*/
10. $('li').slice(2, 4).css('background‐color', 'green')
11.

I hope you found those useful!.

- Addy

AddyOsmani.com 9 of 9

You might also like