Hey guys. Hopefully if you’re reading this you’ve discovered some of the true power jQuery has to offer and you’re now looking for ways to improve your JavaScript skills even further.
There was such a huge response to my last post on jQuery Snippets that I thought it only right to follow up with a fresh list that focuses on some of the more recent features introduced in jQuery 1.4.x. Because it’s always useful to have a second pair of eyes look over your code, I asked Paul Irish from the jQuery Team to take a look at all of today’s snippets and he’s included some useful optimizations to a few of the snippets which I’ve intregated.
Now, if I only we could fit Paul into a useful Browser plugin, all my articles would be just as sensible
The snippets from today can be applied to a wide range of projects so remember to bookmark the post if you find it useful so you can easily come back to it anytime you want. So without further adieu, I give you today’s 31 Snippets that will help make you a JavaScript Pro.
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.
$('.clickme').live('click', function() { // Live handler called. });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:
$('', { text: 'jQuery is awesome!', href: 'http://www.jquery.com', id: 'someAwesomeID', rel: 'external', title: 'This is a title' }).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!
jQuery('#foo').bind({ click: function() { // do something }, mouseover: function() { // do something }, mouseout: function() { // do something } })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):
var obj = jQuery.parseJSON(' {"name":"Larry King", "age": "5000" }'); alert( obj.name === "Larry King" ); //true alert (obj.age === "50");//false alert (obj.age === "5000"); //trueEver 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:
$('#myJaw').slideUp(300).delay(800).fadeIn(400);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:
$('%MINIFYHTMLba7fb904fd003a4d1707ccc7c95f221d29%') .appendTo('head');Here’s how you can remove the parent elements of any object using jQuery’s .unwrap() function
/* 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();Would you like to perform an action when an element or its contents gain focus? Here’s how to do it:
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.'); });Each traversal method in jQuery creates a new set which builds a stack. You can use .end() to reach the previous set.
$("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
$("div").data("myName", 'addy'); $("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.
/* Here are two ways to remove all of the information bound to an element*/ $("div").removeData(); $("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.
$("div").bind("getData.value", function() { return myPlugin.realValue; });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.
/* 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 });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.
$("div").bind("click.plugin", someFn); $("div").bind("focus.plugin", otherFn); $("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.
$("div").bind("myplugin", someFn); $("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.
$("div").bind("remove.pluginA", someFn); $("div").bind("remove.pluginB", otherFn); $("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()!
$("table").delegate("td", "hover", function(){ $(this).toggleClass("active"); });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.
var obj = { method: function(){} }; $("#foo").click( jQuery.proxy( obj, "method" ) ); $("#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.
jQuery.expr[":"].myplugin = function(elem) { return !!jQuery.data("myplugin"); };Did you know that you can treat jQuery objects like arrays?. Take a look at this example.
/*Here's some sample HTML followed by some jQuery that allows us to access the values of any "box" by index.*/
Content #1!Content #2!Content #3!Content #4!Content2 #1!
// 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];
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.
var $myBox = $('#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.
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!');
});
Very useful tip: Did you know that you can select elements within another element just by passing a second parameter to the jQuery initializer?
Here are three ways to access an element within an element:
$('#yourparent').find('#mychild')
//or even shorter:
$('#mychild', $('#yourparent'))
//or even shorter:
$('#mychild', '#yourparent')
How do you handle access to elements with IDs that contain special characters in jQuery?
$("$some[id]").show(); // won't work for this type of ID
$("$some\\[id\\]").show() // works fine for the ID: some[id]
How do you enable or disable form elements within jQuery?
//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");
How do you check if something exists in the DOM using jQuery:
/*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 of text using jQuery?
/*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'));
}
});
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.
//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();
}
});
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:
$(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');
});
- Parent Menu
- Child Item 1
- Child Item 2
How to easily and quickly add one-click clearing of default input text values from your fields
(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();
Would you like to style only a particular range of elements within a list? jQuery’s .slice() function makes this possible through indices
- Apples
- Pears
- Cherries
- Grapes
- Mangos
/*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!. If so, feel free to hit the 31 jQuery Snippets That Will Make You A JavaScript Pro (via @addyosmani)button so you can share it with all your friends and colleagues.
Good luck with your JavaScript!
- Addy


I just really dig JavaScript. I'm a writer, speaker and a JavaScript developer for AOL (yes, we're still around!).
Lots of jQuery here. I like it.
Check out my websitehttp://timothy-mcclimon.appspot.com for more info about CSS, HTML, jQuery, and other computer science topics.
Nice article as usual..
The first example should be : $("<a />", { instead of $('' . {
Thanks for spotting that Erik. I think my syntax highlighter chewed up some of the code. Let me see if I can fix it.
Pingback: 31 jQuery Snippets That Will Help Make You A JavaScript Pro … | RefreshTheNet
Just got here. Awesome site. I'm just starting to use Jquery and this is a great resource. Thanks!
You're welcome, Patrick!. I hope you find the posts on here useful and good luck with jQuery!.
Wow… I am bookmarking this *right now*! I'm glad that you're so into jQuery, Addy. I, for one, very much appreciate it!
No problem at all!. I hope it comes in useful with a few of your projects
Pingback: Blog bookmarks 04/10/2010 « My Diigo bookmarks
Pingback: Veckans länktips – 2010-04-10 | lillbra.se
Pingback: 31 jQuery Snippets That Will Help Make You A JavaScript Pro | newsFTW
Nice list.
On 8: line 4, take the semicolon off after the focusin function to allow chaining.
Here's an added tip.
$.append() takes arrays. So you can append multiple elements at once.
Example:
$( "element" ).append( "
First add me
", "<span>Then ME.</span>", $("<input type='button'>").attr({ "value": "and me! Click me."}).click( function(){ alert( "That's it." ); }) )
Thanks, Larry!. I'm sure everyone will find those very useful.
Nice collection!! jQuery keeps surprising me with loads of good, hidden treasures
Thanks, Venkata!. Good luck with learning more about jQuery, it's a great framework.
Very usefull! Thank you for al the work you put in this article. I've bookmarket it for future use.
You're very welcome, Jerome. I hope it comes in handy in the future!
Pingback: 31 jQuery Snippets That Will Help Make You A JavaScript Pro | AddyOsmani.com | Where Web Businesses Grow | Listaurus
Hi Addy, your collection is just brilliant! We have written a remake for our users athttp://www.snippetsapp.com/blog/30-jquery-snippet…
Are you OK with this? Thanks!
Hi Vadim. I see you guys have mentioned the site on there so its more than okay for you to share it. I'm glad you found it useful!.
Pingback: Bookmarks vom 07.04.2010 bis zum 13.04.2010
Pingback: davidvoegtle.net » Blog Archive » Daily links 04/14/2010
Hi, very useful post. But don't understand ex. #9.
For #23, another way : $('#yourparent #mychild') is fastest !
Pingback: 31 trozos de código de jQuery que te harán ser un profesional en JavaScript
Pingback: 31 trozos de código de jQuery que te harán ser un profesional en JavaScript - Vaya Huevos
Pingback: Maya Lab » Blog Archive » 31 trozos de código de jQuery que te harán ser un profesional en JavaScript
Pingback: You are now listed on FAQPAL
Pingback: Links and Bits for April 19th — Alex Jones
thanks for the information ….. it was very useful
Pingback: Curiosidades y cosas útiles de jQuery « Capy
Pingback: links for 2010-05-03 « Mike Does Tech
Pingback: 31 jQuery Snippets « Blog de Andrés López Gómez
Привет,я Настя Москва 21год. Хочу познакомится с молодым человекам 22-25 лет для серьёзных отношений , мои фото sexiphone.ru
Really nice article
really really useful
Pingback: 31 trozos de código de jQuery | Feimstudio - Diseño y programación web
Nice tipps, thanks for sharing
You're welcome!
This is very amazing!
Pingback: TechnoRabbit » 31 jQuery Snippets
For Item 2 : why not as follows:
$('<a>', {
text: 'jQuery is awesome!',
href: 'http://www.jquery.com',
id: 'someAwesomeID',
rel: 'external',
title: 'This is a title'
}).appendTo('body');
I'm a huge jquery fan and I'm constantly working out new ways to learn it and get more out of the framework. I have the "Jquery: Novice to Ninja" at home I'm starting to go through.
Very informative. Many scripts helped in my project. Thanks
You are very welcome.
This is gold. Thanks for the great selection!
Pingback: Nowości | Wiadomości o technologiach IT
Pingback: Deweloperka na poważnie – jQuery i nie tylko | Wiadomości o technologiach IT
Pingback: Zebrane linki z Chrome w domu | Wiadomości o technologiach IT
More than interesting for a newby like me who needs only the most useful features in jquery!
Thanks.
I want to comment the namespace tip. I prefer to use a prefix, it can be shorter and can saves a couple of bytes for each entry. For example to store data for a specific class, for example this class: function myfriend() {…}, you can use a prefix like cmf:
c stands for class (type)
m stands for My
f stand for Friend
This is a short way to avoid conflicts because a classname is already/must be unique, so you don't need large namespaces.
Cheers!
Erwinus
Thank you for the post man! Found very interesting!
jQuery keeps surprising me with loads of good, hidden treasures
Nice collection!! jQuery keeps surprising me with loads of good, hidden treasures
Thanks much! Subscribed via rss.
31 Snippets that will definitely help to make a JavaScript Pro.