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 e w plai plain n
01. 02. 03.
2.
pri print
?
$('.clickme' $('.clickme').live( ).live('click' 'click', , function() { // Live handler called. });
Attributes in jQuery - jQuery jQuer y supports passing attributes for an object as the second argument to the jQuery function itself. This creates a new link on the page: view e w plai plain n
01. 02. 03. 04. 05. 06. 07.
3.
copy opy to clipboa pboard rd
copy opy to clipboa pboard rd
pri print
?
$('
' $('
', , { text: 'jQuery is awesome!', awesome!', href: 'http://www.jquery.com' 'http://www.jquery.com', , id: 'someAwesomeID' 'someAwesomeID', , rel: 'external' 'external', , title: 'This is a title' }).appendTo('body' }).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 e w plai plain n
01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11.
copy opy to clipboa pboard rd
pri print
?
jQuery('#foo' jQuery('#foo').bind({ ).bind({ click: function() { // do something }, mouseover: function() { // do something }, mouseout: function() { // do something } })
4.
Have you ever wanted to convert your JSON string into a JavaScript 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 e w plai plain n
01. 02. 03. 04. 05. 06. 07.
5.
pri print
?
When styling a large number of elements, instead of using css() it is more mor e efficient effici ent to append a style tag to the DOM as follows: 01. 02.
copy opy to clipboa pboard rd
pri print
?
$('') ') .appendTo('head' .appendTo('head'); );
Here's how you can remove the parent elements of any object using jQuery's .unwrap() function view e w plai plain n
01. 02. 03. 04. 05.
i
copy opy to clipboa pboard rd
$('#myJaw' $('#myJaw').slideUp(300).delay(800).fadeIn(400); ).slideUp(300).delay(800).fadeIn(400);
view e w plai plain n
Add O
?
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 i s use delay as follows: 01. 02.
7.
pri print
var obj = jQuery.parseJSON(' jQuery.parseJSON(' {"name":"Larry King", "age": "5000" }'); }' ); alert( obj.name === "Larry King" ); //true alert (obj.age === "50" "50"); );//false //false alert (obj.age === "5000" "5000"); ); //true
view e w plai plain n
6.
copy opy to clipboa pboard rd
copy opy to clipboa pboard rd
pri print
?
/* 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' jQuery('p').unwrap(); ).unwrap();
2 f9
8.
Would you like to perform an action when an element or its contents gain focus? Here's how to do it: view e w plai plain n
01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20.
9.
//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() $('#target').blur(function() { alert('Handler alert(' Handler for .blur() called.'); called.'); }); //For when an element gains focus use .focus() $('#target $(' #target').focus(function() ').focus(function() { alert('Handler alert(' Handler for .focus() called.'); });
pri print
?
I've mentioned this a few times before, but it's a feature that many developers forget exists within jQuery - data() - jQuery actually actually has an an API for invisibly storing data on DOM nodes n odes so you can easily store any information in formation through JS and it'll be available available through the same central resource 01. 02.
copy opy to clipboa pboard rd
pri print
?
$("div" $("div").data( ).data("myName" "myName", , 'addy' 'addy'); ); $("div" $("div").data( ).data("myName" "myName") ) === 'addy' 'addy'; ;
Garbage collection of data stored can either be done through removeData() or via the remove() function after the element has been deleted. view e w plai plain n
01. 02. 03. 04.
i
copy opy to clipboa pboard rd
$("
") // li .find("a" .find("a") ) // a .attr("href" .attr("href", , "http://www.google.com/" "http://www.google.com/") ) // a .html("Google!" .html("Google!") ) // a .end() // li .appendTo("ul" .appendTo("ul"); );
view e w plai plain n
Add O
?
Each traversal method in jQuery creates a new set which builds a stack. You can use .end() to reach the previous previo us set. 01. 02. 03. 04. 05. 06. 07.
11.
pri print
jQuery('form' jQuery('form') ) .focusin(function(){ jQuery(this).addClass('focused' ).addClass('focused'); ); }); .focusout(function(){ jQuery(this).removeClass('focused' ).removeClass('focused'); ); });
view e w plai plain n
10.
copy opy to clipboa pboard rd
copy opy to clipboa pboard rd
pri print
?
/* Here are two ways to remove all of the information bound to an element*/ $("div" $("div").removeData(); ).removeData(); $("div" $("div").remove(); ).remove();
3 f9
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 e w plai plain n
01. 02. 03. 04.
13.
pri print
?
$("div" $("div").data( ).data("events.plugin" "events.plugin", , { //your data here });
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. 01. 02. 03.
copy opy to clipboa pboard rd
pri print
?
$("div" $("div").bind( ).bind("click.plugin" "click.plugin", , someFn); $("div" $("div").bind( ).bind("focus.plugin" "focus.plugin", , otherFn); $("div" $("div").unbind( ).unbind(".plugin" ".plugin"); );
You can bind to almost any event and there aren't aren 't really any limits on what you can or can't bind to. view e w plai plain n
01. 02.
i
copy opy to clipboa pboard rd
/* 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. */
view e w plai plain n
Add O
?
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. 01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14.
15.
pri print
$("div" $("div").bind( ).bind("getData.value" "getData.value", , function() { return myPlugin.realValue; });
view e w plai plain n
14.
copy opy to clipboa pboard rd
copy opy to clipboa pboard rd
pri print
?
$("div" $("div").bind( ).bind("myplugin" "myplugin", , someFn); $("div" $("div").trigger( ).trigger("myplugin" "myplugin"); );
4 f9
16.
A good tip for complicated applications: Custom events are a useful way way for multiple pieces piece s of code to bind bi nd to the same functionality, so you trigger one event but lots of handlers can be executed. view e w plai plain n
01. 02. 03.
17.
?
copy opy to clipboa pboard rd
pri print
?
var obj = { method: function(){} }; $("#foo" $("#foo").click( ).click( jQuery.proxy( obj, "method" ) ); $("#foo" $("#foo").unbind( ).unbind( "click" "click", , obj.method );
Interested in creating a simple custom selector?. Creating your own selectors is easy and you can do this for your plugins p lugins if you would like some easy querying features. fe atures. view e w plai plain n
01. 02. 03.
copy opy to clipboa pboard rd
pri print
?
jQuery.expr[":" jQuery.expr[":"].myplugin ].myplugin = function(elem) { return !!jQuery.data("myplugin" !!jQuery.data("myplugin"); ); };
Did you know that you can treat jQuery objects like arrays?. Take a look at this example. view e w plai plain n
01. 02. 03. 04. 05.
i
pri print
You can dynamically dynamically change the context of a function (if needed) needed ) using something similar simi lar to this. Since jQuery 1.4.* you've also been able to easily remove the proxied function. 01. 02. 03.
Add O
copy opy to clipboa pboard rd
$("table" $("table").delegate( ).delegate("td" "td", , "hover" "hover", , function(){ $(this).toggleClass("active" ).toggleClass("active"); ); });
view e w plai plain n
20.
?
Have you been trying to find a way to listen to events from a particular context? The delegate and undelegate methods m ethods make this possible (supported in jQuery 1.4.2 onwards). There's also a very large performance gain got from switching over to .delegate()! 01. 02. 03.
19.
pri print
$("div" $("div").bind( ).bind("remove.pluginA" "remove.pluginA", , someFn); $("div" $("div").bind( ).bind("remove.pluginB" "remove.pluginB", , otherFn); $("div" $("div").trigger( ).trigger("remove" "remove"); );
view e w plai plain n
18.
copy opy to clipboa pboard rd
copy opy to clipboa pboard rd
pri print
?
/*Here's some sample HTML followed by some jQuery that allows us to access the values of any "box" by index.*/
Content #1!
class= ="box">Content #2!
view e w plai plain n
01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16.
21.
?
// num is equal to 4 var num = $('#wrapper $('#wrapper .box'); .box'); num = num.length; // text is equal to 'Content #2!' var text = $("#wrapper $("#wrapper .box")[1]; .box")[1]; // text is equal to 'Content #1' var text = $("#wrapper $("#wrapper .box")[0]; .box")[0]; // text is equal to 'Content2 #1' var text = $("#wrapper2 $("#wrapper2 .box")[0]; .box")[0];
Selection storage: Did you know k now that you can store the results from a jQuery selection in a variable and *still* have have access to the same methods?. Here's He re's a useful example. 01. 02. 03. 04.
copy opy to clipboa pboard rd
pri print
?
var $myBox = $('#test' $('#test'); ); /*the variable myHTML is equal to the content's of '#test'*/ 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 e w plai plain n
01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11.
23.
pri print
// returns 4 $('#wrapper $('#wrapper .box').length; .box').length;
view e w plai plain n
22.
copy opy to clipboa pboard rd
copy opy to clipboa pboard rd
pri print
?
function runAlertNow () { $(this).html('I ).html('I just ran this function!'); function!'); }
// both of these lines do the same thing $('#test' $('#test').slideUp(400, ).slideUp(400, runAlertNow); $('#test' $('#test').slideUp(400, ).slideUp(400, function () { $(this).html('I ).html('I just ran the anonymous function!'); function!'); });
Very useful tip: Did you know that you can select elements within another element eleme nt just by passing passing a second parameter paramete r to the jQuery initializer? view e w plai plain n
01.
copy opy to clipboa pboard rd
pri print
?
Here are three ways to access an element within an element: view e w plai plain n
01. 02. 03. 04. 05.
24.
?
How do you handle access to elements with IDs that contain special characters in jQuery? 01. 02.
i
pri print
$('#yourparent' $('#yourparent').find( ).find('#mychild' '#mychild') ) //or even shorter: $('#mychild' $('#mychild', , $('#yourparent' $('#yourparent')) )) //or even shorter: $('#mychild' $('#mychild', , '#yourparent' '#yourparent') )
view e w plai plain n
Add O
copy opy to clipboa pboard rd
copy opy to clipboa pboard rd
pri print
?
$("$some[id]" $("$some[id]").show(); ).show(); // won't work for this type of ID $("$some\\[id\\]" $("$some\\[id\\]").show() ).show() // works fine for the ID: some[id]
6 f9
25.
How do you enable or disable form elements within jQuery? view e w plai plain n
01. 02. 03. 04. 05.
26.
//To re‐enable a disabled form element $("#myelement" $("#myelement").removeAttr( ).removeAttr("disabled" "disabled"); );
copy opy to clipboa pboard rd
pri print
?
/*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 }
How do you search all the nodes on a page for a particular piece pie ce of text using jQuery? view e w plai plain n
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.
i
?
How do you check if something exists in the DOM using jQuery: 01. 02. 03. 04. 05. 06. 07. 08. 09. 10.
Add O
pri print
//To disable a form element such as a text input field $("#myelement" $("#myelement").attr( ).attr("disabled" "disabled", , "disabled" "disabled"); );
view e w plai plain n
27.
copy opy to clipboa pboard rd
copy opy to clipboa pboard rd
pri print
?
/*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" $("#testbutton").click( ).click(function() { var n = $('body').egrep(/jquery/i); $('body').egrep(/jquery/i); for (var i = 0; i < n.length; ++i) { void($(n[i]).css('background void($(n[i]).css(' background', ', 'yellow')); 'yellow')); } });
f9
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. e lements. This is useful when you want to reinsert removed elements into the DOM later. view e w plai plain n
01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13.
29.
01.
copy opy to clipboa pboard rd
pri print
?
$(document).ready(function() { //Let's set the background color of the nearest //UL in this pseudo‐menu $('li.subchild').closest(' $('li.subchild').closest('ul ul').css(' ').css('background‐color background‐color', ', 'red'); 'red'); }); view e w plai plain n
copy opy to clipboa pboard rd
pri print
- Parent Menu
?
- Child Item 1
- Child
How to easily and quickly add one-click clearing clearin g of default input text values values from your fields fi elds view e w plai plain n
01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11. 12. 13. 14. 15. 16. 17.
i
?
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: 01. 02. 03. 04. 05. 06.
Add O
pri print
//In the below example $("p" $("p").click( ).click(function(){ $(this).toggleClass("off" ).toggleClass("off"); ); }); var p; $("button" $("button").click( ).click(function(){ if ( p ) { p.appendTo("body" p.appendTo("body"); ); p = null; } else { p = $("p" $("p").detach(); ).detach(); } });
view e w plai plain n
30.
copy opy to clipboa pboard rd
copy opy to clipboa pboard rd
pri print
?
(function($){ $.fn.clearDefault = function(){ return this.each(function(){ var default_value = $(this).val(); $(this).focus(function(){ if ($(this).val() == default_value) $(this).val("" ).val(""); ); }); $(this).blur(function(){ if ($(this).val() == "" "") ) $(this).val(default_value); }); }); }; })(jQuery); // How to use it: $('input').clearDefault();
8 f9
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 e w plai plain n
01.
view e w plai plain n
01. 02. 03. 04. 05. 06. 07. 08. 09. 10. 11.
copy opy to clipboa pboard rd
pri print
- Apples
copy opy to clipboa pboard rd
?
- Pears
pri print
- Cherries
?
/*If we just want to set the background‐color of everything after element number two (pears) we can do this using:*/ $('li' $('li').slice(2).css( ).slice(2).css('background‐color' 'background‐color', , 'yellow' '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' $('li').slice(2, ).slice(2, 4).css('background‐color' 4).css('background‐color', , 'green' 'green') )
I hope you found those useful!. - Addy
Add O
i
9 f9
- Grapes
- Mangos