Tagged as

Common Pitfalls of jQuery

jQuery is a wonderful library that makes web development with JavaScript a much better experience--but there are some common pitfalls that you should avoid.

Introduction

Nowadays, jQuery is the de facto JavaScript library. CodeProject uses jQuery, Microsoft uses jQuery, Google uses jQuery, and if you've ever made an interactive client-side web application, the chances are that you used jQuery to do it.

This means that the jQuery community is huge, active and vibrant--and that's a great thing. But it also means that people often start creating things with jQuery without first becoming familiar with Javascript and the DOM. It's wonderful, of course, that jQuery is so accessible that even newbies can use it. That said, people will use the most convoluted things with jQuery that could be done simply with just the DOM library, by using a slightly more obscure jQuery feature, or by just being more familiar with how Javascript itself works.

The goal of this article is to exhibit the most common pitfalls people encounter with jQuery. This article assumes that you know what jQuery is and have some basic familiarity with using it.

Mistakes with selectors

Missing parts of selectors

There is one single silly mistake with jQuery selectors that I've made so many times and that has wasted much more debugging time than I would like to admit. Do you see the problem with the following sample?

$("example").text("Hello, world!");

It's easy to miss. In case you didn't notice, there is no hash (#) or dot (.) in the selector to specify that it is searching for an element with a particular id or a set of elements with a particular class. The given selector will look for elements with the tag name example -- which won't exist in any normal circumstances.

Unscoped selectors

Let's suppose you had some markup like this, in the midst of lots of other markup

and you decided to select all the divs with the class box. So you just use the class selector.

$(".box")

This will work, but it will search the entire page for elements with the box class. This can be a very expensive operation. If you know that all the elements with the box class are inside of the container div, you can speed things up by limiting your search boundaries. There are a few different ways to do this in jQuery.

Similarly, you can use this.id instead of $(this).attr("id"). Be careful, though: some properties are not standard will not work across browsers. For example, the non-standard .class property will work on some browsers but not others, but the standard .className should work universally.

The A in AJAX stands for Asynchronous

You should take advantage of asynchronous requests. Too often people will be frustrated with functions not executing in the order they expected and then disable the asynch property

$.ajax({
async: false
});

Disabling async this makes things slower and locks up the browser during the request--so it's usually a bad idea. You should use callbacks instead to manage how you want things to be executed. Explaining how callbacks work is outside the scope of thise article, but there are goodreources explaining it.

Understanding Dynamic Changes

Suppose that you have this code,

$("button").click(doSomething);

and then you dynamically add some buttons to the page. You will notice that the added buttons will not fire the doSomething function. Why is this? The click function only bind the event to the button elements that already exist. If you want it to also bind the event for every button that will be added to the page, you need to use the delegate jQuery method

$(document).delegate("button", "click", doSomething);

This will bind the doSomething function to every button that will ever exist inside of the document. If you only wanted to bind it with with buttons inside a certain selector, then you would replace document with whatever selector you wanted.

That's all, folks!

These are the most common jQuery pitfalls that I have seen and been bit by. If there is an obvious one that I am missing, let me know about it and I might update this article.

Comments and Discussions

Hi, I have one question.
I am making an AJAX call on windiw.onbeforeunload.

As user close tab from browser this code(containing AJAX call) will call! but sometime it failed to make an AJAX call beacuse time taken by tab to close is very low. To resolve that i modify my ajax call and make " async: false ",

Back when I wrote the article in 2012, before jQuery 1.7 came out, on didn't exist yet and delegate was the best method to use at the time. Nowadays you should use on. You can look through the online jQuery documentation[^] for more details.

Note: the CodeProject article editor stinkin' SUCKS!! I've tried 5 different browsers on 2 different OS's to try and get the code segments formatted, but no go. And, don't go commenting it's "user error". I've recorded everything via Camtasia as proof. I did have 3 other sections, but I'm so pissed at the article editor, forget it CodeProject, your "editor" sucks!

Variable Arrays

The one thing that I detest in jQuery is having to retype a DOM object's [static] ID. That's where a variable array comes in handy use. [Now, in .NET v3.5 and earlier world this approach may not work as effectively if you have user controls or master pages which, dismayingly, most traditional .NET web form page have and, dismayingly, create coptic and ever-changing variable names.] Here's an example JS array variable; note the double "$$" as the variable name: