30 Pro jQuery Tips | Tricks and Strategies – B | Tut
Whether you’re a developer or a designer, a strong jQuery skillset is something you can’t afford to be without. Today, I’m going to show you 30 handy jQuery coding tricks that will help you make your scripts more robust, elegant and professional.
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(){
$("body").append("<div class='dialog'></div>").<em>animate({ opacity : 1.0 }, 5000)</em>.fadeOut();
});
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(){
var reversedSet = $("li").get().reverse();
//Use get() to return an array of elements, and then reverse it
$(reversedSet).each(function(){
//Now we can plug our reversed set right into the each function. Could it be easier?
});
});
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(){
if( $(".active").length ){
//Now the code here will only be executed if there is at least one active element
}
});
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(){
var iFrameDOM = $("iframe#someID").contents();
//Now you can use <strong>find()</strong> to access any element in the iframe:
iFrameDOM.find(".message").slideUp();
//Slides up all elements classed 'message' in the iframe
});
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(){
jQuery.fn.equalHeight = function () {
var tallest = 0;
this.each(function() {
tallest = ($(this).height() > tallest)? $(this).height() : tallest;
});
return this.height(tallest);
}
//Now you can call equalHeight
$(".content-column").equalHeight();
});
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():
$(function(){
//First define your search string, replacement and context:
var phrase = "your search string";
var replacement = "new string";
var context = $(body);
//
context.html(
context.html().replace('/'+phrase+'/gi', replacement);
);
});
7_ Hack Your Titles to Prevent Widows
Nobody likes to see widows – but thankfully with some jQuery and a little help from we can stop that from happening:
$(function(){
//Loop through each title
$("h3").each(function(){
var content = $(this).text().split(" ");
var widow = "&nbsp;"+content.pop();
$(this).html(content.join(" ")+widow);
});
});
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);
<strong>//ADD FIRST-CHILD SUPPORT:</strong>
jQuery.fn.firstChild = function(){
return this.each(function(){
var currentClass = $(this).attr('class').split(' ')[0]; //Get first class name
$(this).children(":first").addClass(currentClass + '-first-child');
});
}
$(".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-first-child’ classes as additional selectors:
.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:
$(function(){
//set default value:
$("#searchbox")
.val('search?');
.focus(function(){this.val('')})
.blur(function(){
(this.val() === '')? this.val('search?') : null;
});
});
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);
});
});
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:
$(function() {
//We can get X/Y coordinates on click events:
$("a").click(function(<em>e</em>){
var clickX = e.pageX;
var clickY = e.pageX;
});
//Or detect which key was pressed:
$("window").keypress(function(<em>e</em>){
var keyPressed = e.which;
});
});
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:
$(function(){
var text = $("#someElement").text();
var text2 = "Some <code> & such to encode";
//you can define a string or get the text of an element or field
var html = $(text).html();
var html2 = $(text2).html();
//Done - html and html2 now hold the encoded values!
});
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):
$(function(){
// Reset Font Size
var originalFontSize = $('html').css('font-size');
$(".resetFont").click(function(){
$('html').css('font-size', originalFontSize);
});
// Increase Font Size
$(".increaseFont").click(function(){
var currentFontSize = $('html').css('font-size');
var currentFontSizeNum = parseFloat(currentFontSize, 10);
var newFontSize = currentFontSizeNum*1.2;
$('html').css('font-size', newFontSize);
return false;
});
// Decrease Font Size
$(".decreaseFont").click(function(){
var currentFontSize = $('html').css('font-size');
var currentFontSizeNum = parseFloat(currentFontSize, 10);
var newFontSize = currentFontSizeNum*0.8;
$('html').css('font-size', newFontSize);
return false;
});
});
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.
$(function(){
$('a[rel$='external']').click(function(){
this.target = "_blank";
});
});
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:
$(function(){
$("a").bind("click",function(){
//Put your AJAX request code here
return false;
});
});
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 jQue…
-
http://reliacardcom.net Reliacard
-
http://vkstatysov.net.ua/ Status
-
http://www.furnitureanddecor.biz/ Furniture
-
http://www.noeytivi.com Free Streaming Online TV Series
-
http://www.freerolltournaments.org Poker
-
http://watchlostonlinestreaming.com/category/season1/ lost season 1
-
http://www.squidoo.com/easytolearnmagictricks Sammie Dummitt
-
http://cafepress.com/EtherCycleLLC Bertha
-
http://www.gather.com/viewArticle.action?articleId=281474978704526 my page
-
http://www.blogster.com/andersonhaney/ Filip





















