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):

$(function(){ 1 jQuery.fn.equalHeight = function () { 2 var tallest = 0; 3 this.each(function() { 4 tallest = ($(this).height() > tallest)? 5 $(this).height() : tallest; 6 }); 7 return this.height(tallest); 8 } 9 10 //Now you can call equalHeight 11 $(".content-column").equalHeight(); 12 });

An interesting and similar concept is the awesome jQuery masonry plugin, if you‟re interested in checking it out.

#6 – Find a Selected Phrase and Manipulate It
Whether you‟re looking to perform find and replace, highlight search terms, or something else, jQuery again makes it easy with html():
1 $(function(){ 2 //First define your search string, replacement and context: var phrase = "your search string"; 3 var replacement = "new string"; 4 var context = $(body); 5 6 7 // 8 context.html( 9 context.html().replace('/'+phrase+'/gi', replacement); 10 ); 11 12 });

#7 – Hack Your Titles to Prevent Widows
Nobody likes to see widows – but thankfully with some jQuery and a little help from &nbsp; we can stop that from happening:
1 $(function(){ 2 //Loop through each title $("h3").each(function(){ 3 var content = $(this).text().split(" "); 4 var widow = "&amp;nbsp;"+content.pop(); 5 $(this).html(content.join(" ")+widow); 6 7 }); 8 });

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);

1 2 3 4 5 6 7 8 9 10 11 12 13 <strong>//ADD FIRST-CHILD SUPPORT:</strong> jQuery.fn.firstChild = function(){ 14 return this.each(function(){ 15 var currentClass = $(this).attr('class').split(' 16 17 ')[0]; //Get first class name $(this).children(":first").addClass(currentClass 18 19 + '-first-child'); 20 }); 21 } $(".searchform").firstChild(); });

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 });

#10 – Create a Disappearing ‘Back-to-Top’ Link
The disappearing back-to-top link was inspired by Brian Cray. All you have to do is add a back-to-top link at the bottom of your content like normal, and then jQuery performs the magic:
$(function(){ /* set variables locally for increased performance */ var scroll_timer, displayed = false, $message = $('#message a'), $window = $(window), top = $(document.body).children(0).position().top; /* react to scroll event on window */ $window.scroll(function () { window.clearTimeout(scroll_timer); scroll_timer = window.setTimeout(function () { // use a timer for performance if($window.scrollTop() <= top) // hide if at the top of the page { displayed = false; $message.fadeOut(500); } else if(displayed == false) // show if scrolling down { displayed = true; $message.stop(true, true).show().click(function () { $message.fadeOut(500); }); } }, 100); }); });

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25

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.

#11 – Easily Respond to Event Data
One of my favorite things about jQuery is its convenient remapping of event data, virtually eliminating cross-browser inconsitencies and making events much easier to respond to. jQuery passes an event parameter into all bound/triggered functions, which is commonly called e:
1 $(function() { 2 //We can get X/Y coordinates on click events: $("a").click(function(<em>e</em>){ 3 var clickX = e.pageX; 4 var clickY = e.pageX; 5 6 }); 7 8 //Or detect which key was pressed: $("window").keypress(function(<em>e</em>){ 9 var keyPressed = e.which; 10 11 }); 12 });

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 });

7 // Increase Font Size $(".increaseFont").click(function(){ 8 var currentFontSize = $('html').css('font-size'); 9 var currentFontSizeNum = parseFloat(currentFontSize, 10); 10 var newFontSize = currentFontSizeNum*1.2; 11 12 $('html').css('font-size', newFontSize); return false; 13 14 }); 15 // Decrease Font Size $(".decreaseFont").click(function(){ 16 var currentFontSize = $('html').css('font-size'); 17 var currentFontSizeNum = parseFloat(currentFontSize, 10); 18 var newFontSize = currentFontSizeNum*0.8; 19 20 $('html').css('font-size', newFontSize); return false; 21 22 }); 23 });

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 = "_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 and do some parsing on it:
var searchArray ="&"); //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.

#21 – Optimize Your Performance
Experienced coders don‟t make clients wait – they write code that runs fast! There are several ways you can make your code run faster like:
    

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
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‟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:

1 (function($){ $(document).ready(function(){ 2 3 //You can use normal jQuery syntax here 4 }); 5 })(jQuery);

#24 – Efficiently Store Element-Specific Information with data()
data() is probably one of the lesser used jQuery methods, although it certainly shouldn‟t be. It allows us to attach/retrieve as much data as we want to DOM elements without misusing attributes, and is especially useful for more complex scripts. For example, Stefan Petre‟s Colorpicker plugin uses data a lot because it‟s tracking lots of fields and colors, converting rgb to hex, etc. Here‟s are some examples of how data() works:
1 $(document).ready(function() { 2 //Set status to 'unsaved' 3 $("button:first").data("status", "unsaved"); 4 5 //Retrieve status var buttonStatus = $("button:first").data("status"); 6 7 8 //Change status, this time defining an object literal $("button:first").data("status", {saved : true, index : 1}); 9 10 11 //Retrieve status of index property var buttonStatusIndex = $("button:first").data("status").index; 12 13 14 //Remove status data 15 $("button:first").removeData("status"); 16 });

I‟m sure you can imagine the huge extent of possibilities this presents. Again, it‟s worth reading the documentation if you haven‟t used data() before.

#25 – Extend/Modify Existing jQuery Functions
Nobody says you can‟t use the existing jQuery platform as a springboard for new ideas – and many have done just that using extend(), another wonderful jQuery method. The popular Easing plugin, for example, adds some animation variety by extending the easing object, an already existing object that is passed to animate() and others:
1 jQuery.extend({ 2 easing: { easein: function(x, t, b, c, d) { 3 return c*(t/=d)*t + b; // in 4 5 }, easeinout: function(x, t, b, c, d) { 6 if (t < d/2) return 2*c*t*t/(d*d) + b; 7 var ts = t - d/2; 8 return -2*c*ts*ts/(d*d) + 2*c*ts/d + c/2 + b; 9 10 },

11 12 13

easeout: function(x, t, b, c, d) { return -c*t*t/(d*d) + 2*c*t/d + b; }...

By extending and improving jQuery‟s default functionality, you can open up a whole new world of cool possibilities.

#26 – Reverse Engineer before() and after()
I always appreciated how jQuery provided append()/prepend() and appendTo()/prependTo(), enabling us to easily perform an append in either direction. I‟ve wished, though, that a similar ability was provided with before() and after(). To change that, we can easily add two functions called putBefore() and putAfter() that will fulfill that purpose. Here‟s how:
1 $(function(){ jQuery.fn.putBefore = function(dest){ 2 return this.each(function(){ 3 $(dest).before($(this)); 4 5 }); 6 } jQuery.fn.putAfter = function(dest){ 7 return this.each(function(){ 8 $(dest).after($(this)); 9 10 }); 11 } 12 });

#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">

<h3>Popular</h3> 2 <ul> 3 <li>Item #1</li> 4 <li>Item #2</li> 5 <li>Item #3</li> 6 </ul> 7 8 </div> 9 <div class="widget"> <h3>Recent</h3> 10 <ul> 11 <li>Item #1</li> 12 <li>Item #2</li> 13 <li>Item #3</li> 14 </ul> 15 16 </div>

With a bit of styling, this would look just fine, so we know our jQuery is going to degrade gracefully. Now we can write the code:
$(document).ready(function() { $("div.widget").hide().filter(":first").before("<ul class='tabs'></ul><div class='tabcontent'></div>").add("div.widget").each(function(){ $(this).find("ul").appendTo(".tab-content"); $("ul.tabs").append("<li>" +$(this).find(":header:first").text()+ "</li>"); }); $("ul.tabs li").click(function(){ $(this).addClass("active"); $(".tab-content ul").slideUp().eq($("ul.tabs li").index(this)).slideDown(); }); $("ul.tabs li:first").click(); });

1 2 3 4 5 6 7 8 9 10 11

Of course, that‟s just one way to do it. If you‟d like to see some other approaches, see Extra Tuts‟ jQuery Tabs Tutorials collection.