Getting Started

These tips and tricks all have one thing in common- they are all smashingly useful. With this stuff in your back pocket, you‟ll be ready to go change the world, and even better, write jQuery like you know what you‟re doing. It‟s gonna be fun. We‟ll start with some basic tricks, and move to some more advanced stuff like actually extending jQuery‟s methods and filters. Of course, you should be familiar with the basics of jQuery first. If you haven‟t used jQuery before, I highly recommend browsing the documentation and watching jQuery for Absolute Beginners Video Series. Otherwise, you‟re ready to dig in!

#1 – Delay with Animate()

This is a very quick, easy way to cause delayed actions in jQuery without using setTimeout. The way we make it work is to add an animate function into your chain and animate the element to 100% opacity (which it‟s already at), so it looks like nothing is happening. For instance, let‟s say that you wanted to open a dialog and then fade it away after 5 seconds. Using animate, you can do it like this:
$(function(){ 1 $("body").append("<div class='dialog'></div>").<em>animate({ 2 opacity : 1.0 }, 5000)</em>.fadeOut(); 3 });

Don‟t you just love jQuery chaining? You‟re welcome to read more about this technique from Karl Swedberg. UPDATE: jQuery 1.4 has eliminated the need for this hack with a method called delay(). It is just what is sounds like – a function specifically made to delay an animation effect. Way to go, jQuery!

#2 – Loop through Elements Backwards
One of my personal favorites is being able to loop backwards through a set of elements. We all know each() lets us easily loop through elements, but what if we need to go backwards? Here‟s the trick:

$(function(){ 1 var reversedSet = $("li").get().reverse(); 2 //Use get() to return an array of elements, and then reverse it 3 4 $(reversedSet).each(function(){ 5 //Now we can plug our reversed set right into the each 6 function. Could it be easier? 7 }); 8 });

#3 – Is There Anything in the jQuery Object?
Another very elementary but regularly useful trick is checking if there are any elements in the jQuery object. For example, let‟s say we need to find out if there are any elements with a class of „active‟ in the DOM. You can do that with a quick check of the jQuery object‟s length property like this:
$(function(){ 1 if( $(".active").length ){ 2 //Now the code here will only be executed if there is at 3 least one active element 4 } 5 });

This works because 0 evaluates false, so the expression only evaluates true if there is at least one element in the jQuery object. You can also use size() to do the same thing.

#4 – Access iFrame Elements
Iframes aren‟t the best solution to most problems, but when you do need to use one it‟s very handy to know how to access the elements inside it with Javascript. jQuery‟s contents() method makes this a breeze, enabling us to load the iframe‟s DOM in one line like this:
$(function(){ 1 var iFrameDOM = $("iframe#someID").contents(); 2 //Now you can use <strong>find()</strong> to access any element 3 in the iframe: 4 5 iFrameDOM.find(".message").slideUp(); 6 //Slides up all elements classed 'message' in the iframe 7 });

#5 – Equal Height Columns
This was one of CSS Newbie‟s most popular posts of 2009, and it is a good, solid trick to have in your toolbox. The function works by accepting a group of columns, measuring each one to see which is largest, and then resizing them all to match the biggest one. Here‟s the code (slighly modified):

This technique was suggested in a comment by Bill Brown on Css-Tricks.

#8 – Add Pseudo-Selector Support in IE
Whether or not to support IE (especially 6) is a hotly debated issue, but if you are of the “let‟s-make-the-best-of-this” camp, it‟s nice to know that you can add pseudo-selector support with jQuery. And we aren‟t just limited to :hover, although that‟s the most common:
$(function(){ <strong>//ADD HOVER SUPPORT:</strong> function hoverOn(){ var currentClass = $(this).attr('class').split(' ')[0]; //Get first class name $(this).addClass(currentClass + '-hover'); } function hoverOff(){ var currentClass = $(this).attr('class').split(' ')[0]; //Get first class name $(this).removeClass(currentClass + '-hover'); } $(".nav-item").hover(hoverOn,hoverOff);

The great thing about setting it up that way firstChild(), hoverOn() and hoverOff() are very reusable. Now, in the CSS we can simply add the „nav-item-hover‟ or „searchform-firstchild‟ classes as additional selectors:
1 2 3 4 5 6 7 8 .nav-item:hover, <strong>.nav-item-hover</strong>{ background:#FFFFFF; border: solid 3px #888; } .searchform:first-child, <strong>.searchform-first-child</strong>{ background:#FFFFFF; border: solid 3px #888; }

It‟s not pretty, but it is valid and it works. I‟ve got to say, though, that I sure am looking forward to the day we won‟t have to bother with this stuff!

#9 – Manage Search Box Values

A popular effect is to fill a site‟s search box with a value (like „search…‟) and then use jQuery to clear the default value when the field receives focus, reverting if the field is empty when blurred. That is easily accomplished with a couple lines of jQuery:
1 $(function(){ 2 //set default value: 3 $("#searchbox") 4 .val('search?'); .focus(function(){this.val('')}) 5 .blur(function(){ 6 (this.val() === '')? this.val('search?') : null; 7 8 }); 9 });

Brian also added some nice-looking CSS, which you could add as a css file or define in an object literal and apply it using jQuery.css(). Feel free to go check out his in-depth explanation if you want to learn more.

You can check out the jQuery docs on this one to see all the possibilites, or view this keycode reference if you‟d like to look up a certain key‟s character code.

#12 – Encode HTML Entities
The first place I saw this mentioned was over at Debuggable, and I have to say they really came up with something good here. The idea is to produce a jQuery result similar to PHP‟s htmlentities(). Check this out:
1 $(function(){ var text = $("#someElement").text(); 2 var text2 = "Some <code> & such to encode"; 3 4 //you can define a string or get the text of an element or field 5 var html = $(text).html(); 6 var html2 = $(text2).html(); 7 8 //Done - html and html2 now hold the encoded values! 9 });

#13 – Friendly Text Resizing
Originally mentioned at ShopDev, this is an excellent way to include some user-centricity in your code (allowing them to control the font-size):
1 $(function(){ 2 // Reset Font Size var originalFontSize = $('html').css('font-size'); 3 $(".resetFont").click(function(){ 4 5 $('html').css('font-size', originalFontSize); 6 });

As I said, this is nice trick to know and adds some of that dynamic friendliness that people enjoy so much.

#14 – Open External Links in a New Window
This external links hack has been mentioned before at Cats Who Code, and although imperfect it‟s a good way to open external links in new windows without causing validation errors in XHTML 1.0 Strict.
1 $(function(){ $('a[rel$='external']').click(function(){ 2 this.target = "_blank"; 3 4 }); 5 });

This works by grabbing all links with an external rel and adding a blank target. Same result, it‟s just not hardcoded into the site.

#15 – Gracefully Degrading AJAX Navigation
AJAX navigation is great – but not for users and bots who can‟t use it. The good news is, it‟s possible to offer direct links to your content while still presenting AJAX functionality (to users who have that capability) by catching links before they go anywhere, returning false on them and loading the AJAX content instead. It could look like this:
1 $(function(){ $("a").bind("click",function(){ 2 3 //Put your AJAX request code here return false; 4 5 }); 6 });

Of course, this is very basic, but it‟s an essential facet to any AJAX navigation. You can also check out SpeckyBoy‟s post on Easy-to-Use Free Ajax Navigation Solutions.

#16 – Create an Array of GET variables
Although this is not specifically a jQuery trick, it‟s useful enough to be included here. Using GET variables in Javascript code doesn‟t happen everyday, but when it does you‟ll want to know a quick and efficient way to read them. All we have to do is get document.location.search and do some parsing on it:
var searchArray = document.location.search.substring(1).split("&"); //Take off the '?' and split into separate queries //Now we'll loop through searchArray and create an associative array (object literal) called GET var GET = []; for (searchTerm in searchArray){ searchTerm.split("="); //Divide the searchTerm into property and value GET[searchTerm[0]] = searchTerm[1]; //Add property and value to the GET array }

1 2 3 4 5 6 7 8 9 10

#17 – Partial Page Refresh Using load()
This excellent technique found at the Mediasoft Blog is way cool and very handy for creating a regularly updating dashboard/widget/etc. It works by using jQuery.load() to perform a AJAX request:
1 $(document).ready(function() { setInterval(function() { 2 3 $("#content").load(location.href+" #content>*",""); 4 }, 5000); 5 });

Voila! It works – no iframes, meta refreshes or other such nonsense.

#18 – Skin with jQuery UI
If you‟re going to write any jQuery plugins (I hope you have already!), you should know that a great way to add flexibility and elegance is to incorporate jQueryUI theming classes into any widgets/visible elements your plugin produces. The great thing about doing this is that it cuts or eliminates the css you have to provide with the plugin, and it adds a lot of customizability, too (which is one of the key factors in a successful plugin). And the actual implementation is as simple as learning how the classes work and attaching them to plugin elements. I can see this would be especially great with plugins like form

beautifiers and photo sliders, making it easy to keep a consistent look throughout a website or app. You can check out the Theming Reference here.

#19 – Include Other Scripts
Stylesheet switchers are nothing new, but adding other scripts with jQuery is something that is often overlooked. The advantage is twofold: 1. It makes it easy to have lazy script loading. 2. It also allows us to add scripts at runtime, which could be useful in a whole host of situations. It‟s as easy as using append() to add a new script to the head of the document:
$(function(){ 1 $("head").append("<script type='text/javascript' 2 src='somescript.js'></script>"); 3 4 //Or, loading only when the slow stuff is ready: $("img,form").load(function(){ 5 6 $("head").append("<script type='text/javascript' 7 src='somescript.js'></script>"); 8 }); });

#20 – Use Body Classes for Easy Styling
Do you want to save on code and keep your styling in the css file where it should be? Body classes (another great ideas suggested by Karl Swedberg) allow you to do that. In short, you can use jQuery to add a „JS‟ class to the body element, which will enable you to set styles in your css that will only be applied if Javascript is enabled. For example:
1 $(document).ready(function() { 2 $("body").addClass("JS"); 3 });

For Javascript users the body now has a JS class, so in our CSS we can add styles like this:
ul.navigation{ display:block; } .JS ul.navigation{ display:none; }

This gives us a great way to change styles based on whether or not Javascript is supported/enabled, and we can still keep the styling in the CSS file. Another interesting related use of this technique is to add browser classes to the body, enabling easy browserspecific styling. You can read more about that here.

Reference id‟s rather than classes (id selection is native and therefore quicker) Use for instead of each() Limit DOM manipulation by adding elements in one big chunk rather than one at a time Take advantage of event delegation Link to Google‟s jQuery copy rather than hosting your own – it‟s faster and always up to date

Basically, it all boils down to not making jQuery do any more work than it has to (and using native abilites whenever possible). Giulio Bai wrote an excellent post on jQuery perfomance, if you‟d like to dig in deeper.

#22 – Adapt Your Scripts to Work Cross-Browser – The Right Way
Thankfully, jQuery‟s cross-browser compatibility really cuts down the need for browser hacks. Sometimes, though, it is good to be able to get information about the client, and we can do that cleanly and unobtrusively with jQuery.support:
1 2 3 4 5 //Does this client follow the W3C box model? var boxModel = $.support.boxModel; //Does this client support 'opacity'? var opacity = $.support.opacity;

It‟s definitely better practice to use feature-detection rather than browser sniffing, and this is a very efficient way to do it. Read more about jQuery.support‟s properties here.

#23 – Configure jQuery to be Compatible with Other Libraries
We all find ourselves in situations where multiple libraries are needed, and because jQuery isn‟t the only library that uses the $ alias, compatiblity issues sometimes pop up. Thankfully, this is easy to fix using jQuery‟s noConflict(). You can even define a custom alias to replace the $:
1 var $j = jQuery.noConflict(); 2 3 //Now you can use '$j' just like '$' 4 $j("div").hide();

An alternate technique is to wrap jQuery calls in an anonymous function and pass jQuery in as a parameter. Then you can use whatever alias you want, including the „$‟. This is especially useful for plugin authoring:

#27 – Add an isChildOf() Test
I‟m sure we all have found ourselves in this situation – needing to know if an element is a descendant of another element. The good news is, with one line of code we can extend jQuery to allow this:
$(function(){ jQuery.fn.isChildOf = function(b){return (this.parents(b).length 1 2 > 0);}; 3 4 //Now we can evaluate like this: if ( $("li").isChildOf("ul") ){ 5 6 //Obviously, the li is a child of the ul so this code is 7 executed 8 } });

Thanks to Dan Switzer II for this contribution!

#28 – Add Custom Selectors

This is another one that has been talked about a lot in the development community, so you may have this already figured out. If not, get ready because this will open some whole new windows for jQuery efficiency. The short story is, jQuery allows us to extend its expression object, which means we can add whatever custom selectors we want. For example, say we wanted to add a selector version of the isChildOf() method we wrote earlier:
1 $(function(){ 2 jQuery.extend(jQuery.expr[':'], { 'child-of' : function(a,b,c) { 3 return (jQuery(a).parents(c[3]).length > 0); 4 5 } 6 }); 7 8 //'child-of' is now a valid selector: 9 $("li:child-of(ul.test)").css("background","#000"); 10 });

Debuggable has a great post on this one as well, if you‟d like to read more about how the parameters work, etc.

#29 – Smooth Scrolling Without Plugin
Karl Swedberg posted this one a while back on the Learning jQuery site, and it is definitely worth a look. Of course, there are a couple of plugins to accomplish this (and they have more features), but I think the real value in this is the excercise of doing it yourself. Plus, look at how tiny it is:
$(document).ready(function() { $('a[href*=#]').click(function() { 1 if (location.pathname.replace(/^\//,'') == 2 3 this.pathname.replace(/^\//,'') && location.hostname == this.hostname) { 4 var $target = $(this.hash); 5 6 $target = $target.length && $target || $('[name=' + 7 this.hash.slice(1) +']'); if ($target.length) { 8 9 $target.ScrollTo(400); return false; 10 11 } 12 }; 13 }); });

#30 – Add Tabs without a Plugin
jQuery tabs are often covered but also often used, and like the scrolling trick above it‟s important to know how to do these without a plugin. The first thing to do is write our markup, which should be perfectly presentable in the absence of Javascript:
1 <div class="widget">