You are on page 1of 12

Jquery Thinking and tips

 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 plaincopy to clipboardprint?

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

 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 plaincopy to clipboardprint?

1. $('', {  
2. text: 'jQuery is awesome!',  
3. href: 'http://www.jquery.com',  
4. id: 'someAwesomeID',  
5. rel: 'external',  
6. title: 'This is a title'  
7. }).appendTo('body');  

 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 plaincopy to clipboardprint?

1. jQuery('#foo').bind({  
2.     click: function() {  
3.         // do something  
4.     },  
5.     mouseover: function() {  
6.         // do something  
7.     },  
8.     mouseout: function() {  
9.         // do something  
10.     }  
11. })  

 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 plaincopy to clipboardprint?

1. var obj = jQuery.parseJSON(' 
2.     {"name":"Larry King", 
3.      "age": "5000" 
4.     }');  
5. alert( obj.name === "Larry King" ); //true  
6. alert (obj.age  === "50");//false  
7. alert (obj.age  === "5000"); //true  

 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 plaincopy to clipboardprint?

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

 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 plaincopy to clipboardprint?

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

 Here’s how you can remove the parent elements of


any object using jQuery’s .unwrap() function
view plaincopy to clipboardprint?

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

 Would you like to perform an action when an


element or its contents gain focus? Here’s how to do
it:
view plaincopy to clipboardprint?

1. jQuery('form')  
2.     .focusin(function(){  
3.         jQuery(this).addClass('focused');  
4.     });  
5.     .focusout(function(){  
6.         jQuery(this).removeClass('focused');  
7.     });  
8.   
9. //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. });  

 Each traversal method in jQuery creates a new set


which builds a stack. You can use .end() to reach the
previous set.
view plaincopy to clipboardprint?

1. $(" 
2. <ul> 
3. <li> </li> 
4. </ul> 
5.  
6. ") // li  
7.   .find("a") // a  
8.     .attr("href", "http://www.google.com/") // a  
9.     .html("Google!") // a  
10.   .end() // li  
11.   .appendTo("ul");  
12.     

 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 plaincopy to clipboardprint?

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

 Garbage collection of data stored can either be


done through removeData() or via the remove()
function after the element has been deleted.
view plaincopy to clipboardprint?

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

 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 plaincopy to clipboardprint?

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

 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 plaincopy to clipboardprint?

1. /* 
2. Why namespace? Namespacing ensures that your 
3. variables don't conflict with any others which 
4. happen to have the same name. This is important 
5. if you want to avoid your code breaking when 
6. other files or plugins are included in your 
7. page's architecture. See below for an example of 
8. namespacing data. 
9. */  
10.   
11. $("div").data("events.plugin",  
12. {  
13.    //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 plaincopy to clipboardprint?

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

 You can bind to almost any event and there aren’t


really any limits on what you can or can’t bind to.
view plaincopy to clipboardprint?

1. $("div").bind("myplugin", someFn);  
2. $("div").trigger("myplugin");  
 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 plaincopy to clipboardprint?

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

 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 plaincopy to clipboardprint?

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

 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 plaincopy to clipboardprint?

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

 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 plaincopy to clipboardprint?
1. jQuery.expr[":"].myplugin = function(elem) {  
2.   return !!jQuery.data("myplugin");  
3. };  

 Did you know that you can treat jQuery objects


like arrays?. Take a look at this example.
view plaincopy to clipboardprint?

1. /*Here's some sample HTML followed by some jQuery  
2. that allows us to access the values of any "box"  
3. by index.*/  
4. <div id="wrapper">  
5. <div class="box">Content #1!</div>  
6. <div class="box">Content #2!</div>  
7. <div class="box">Content #3!</div>  
8. <div class="box">Content #4!</div>  
9. </div>  
10. <div id="wrapper2">  
11. <div class="box">Content2 #1!</div>  
12. </div>  

view plaincopy to clipboardprint?

1. // returns 4  
2. $('#wrapper .box').length;  
3.   
4. // num is equal to 4  
5. var num = $('#wrapper .box');  
6. num = num.length;  
7.   
8. // text is equal to 'Content #2!'  
9. 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];  

 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 plaincopy to clipboardprint?
1. var $myBox = $('#test');  
2. /*the variable myHTML is equal to the content's of 
3. '#test'*/  
4. var myHTML = $myBox.html();  

 Did you know that jQuery has great support for


Callbacks? Here are two ways you can tell if a
function has completed running.
view plaincopy to clipboardprint?

1. function runAlertNow ()  
2. {  
3.     $(this).html('I just ran this function!');  
4. }  
5.   
6. // both of these lines do the same thing  
7. $('#test').slideUp(400, runAlertNow);  
8. $('#test').slideUp(400, function ()  
9. {  
10. $(this).html('I just ran the anonymous function!');  
11. });  

 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 plaincopy to clipboardprint?

1. <div id="yourparent">  
2. <div id="mychild"> </div>  
3. </div>  

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

view plaincopy to clipboardprint?

1. $('#yourparent').find('#mychild')  
2. //or even shorter:  
3. $('#mychild', $('#yourparent'))  
4. //or even shorter:  
5. $('#mychild', '#yourparent')  

 How do you handle access to elements with IDs


that contain special characters in jQuery?
view plaincopy to clipboardprint?

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

 How do you enable or disable form elements


within jQuery?
view plaincopy to clipboardprint?

1. //To disable a form element such as a text input field  
2. $("#myelement").attr("disabled", "disabled");  
3.   
4. //To re-enable a disabled form element  
5. $("#myelement").removeAttr("disabled");  

 How do you check if something exists in the DOM


using jQuery:
view plaincopy to clipboardprint?

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

 How do you search all the nodes on a page for a


particular piece of text using jQuery?
view plaincopy to clipboardprint?

1. /*This useful extended function will allow you to 
2. pattern match a keyword across all the nodes in a 
3. page. See the example below for how GMail use something 
4. similar in concept for their search-keyword highlighting*/  
5.   
6. $.fn.egrep = function(pat) {  
7.  var out = [];  
8.  var textNodes = function(n) {  
9.   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. });  

 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 plaincopy to clipboardprint?

1. //In the below example  
2. $("p").click(function(){  
3.       $(this).toggleClass("off");  
4.     });  
5.     var p;  
6.     $("button").click(function(){  
7.       if ( p ) {  
8.         p.appendTo("body");  
9.         p = null;  
10.       } else {  
11.         p = $("p").detach();  
12.       }  
13.     });  

 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 plaincopy to clipboardprint?

1. $(document).ready(function()  
2. {  
3. //Let's set the background color of the nearest  
4. //UL in this pseudo-menu  
5. $('li.subchild').closest('ul').css('background-color', 'red');  
6. });  

view plaincopy to clipboardprint?

1. <ul>  
2. <li>Parent Menu  
3. <ul>  
4. <li class="subchild">Child Item 1</li>  
5. <li class="subchild">Child Item 2</li>  
6. </ul>  
7. </li>  
8. </ul>  

 How to easily and quickly add one-click clearing of


default input text values from your fields
view plaincopy to clipboardprint?

1. (function($){  
2.     $.fn.clearDefault = function(){  
3.         return this.each(function(){  
4.             var default_value = $(this).val();  
5.             $(this).focus(function(){  
6.                 if ($(this).val() == default_value)  
7.                               $(this).val("");  
8.             });  
9.             $(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();  

 Would you like to style only a particular range of


elements within a list? jQuery’s .slice() function
makes this possible through indices
view plaincopy to clipboardprint?

1. <ul>  
2. <li>Apples</li>  
3. <li>Pears</li>  
4. <li>Cherries</li>  
5. <li>Grapes</li>  
6. <li>Mangos</li>  
7. </ul>  

view plaincopy to clipboardprint?

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

You might also like