Click here to Skip to main content
11,582,849 members (74,477 online)
Click here to Skip to main content

Tagged as

Common Pitfalls of jQuery

, 19 Apr 2012 CPOL 46.4K 108
Rate this:
Please Sign up or sign in to vote.
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.

Excessive jQuery Calls

It's unfortunately common to see code like this

$("#example").text("Hello, world!");
$("#example").css("color", "red");
$("#example").addClass("fun");

This code is unnecessarily expensive, because it is making repeated calls to jQuery to look for elements that match the "#example" selector.

There are two alternative ways to do this. First, you can cache the query.

var $example = $("#example");
$example.text("Hello, world!");
$example.css("color", "red");
$example.addClass("fun");

When assigning a jQuery object to a variable, the convention is to put a dollar sign ($) before the name to demarcate it as a jQuery object.

Second, you can use method chaining. jQuery methods will return new jQuery objects that you can call more jQuery methods on.

$("#example").text("Hello, world!").css("color", "red").addClass("fun");

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

<!-- lots of HTML here -->
<div id="container">
  <div class="box">
  </div>
  <div class="lid">
  </div>
  <div class="box">
  </div>
  <div class="lid">
</div>
<!-- lots of HTML here -->

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.

$("#container .box")
$("#container").find(".box")
$(".box", $("#container"))

Repetitive Selectors

It's fairly common to see the same effect being performed on multiple selections of elements.

$("#main").css("color", "red");
$("#content").css("color", "red");
$(".important").css("color", "red");

It's better to use the comma (,) selection operator to match multiple selections

$("#main, #content, .important").css("color", "red");

Unused Shortcuts

These lines of code are unfortunately common

$("#el").css("display", "none");
$("#el").css("display", "");

if($("#el").is(":visible")) $("#el").css("display", "none");
else $("#el").css("display", "");

$("#el").html("");
$("#el").prop("class", $("#el").prop("class") + " " + newClass);

when there are faster and more readable shortcuts

$("#el").hide();
$("#el").show();
$("#el").toggle();
$("#el").empty();
$("#el").addClass(newClass);

Unfamiliarity with the DOM

It's a good idea to get acquainted with the DOM, because there are some things that using jQuery for is excessive. For example,

 $('img').click(function() { 
      alert($(this).attr('src'));
}); 

is excessive when you can just use

$('img').click(function() { 
    alert(this.src);
}); 

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 good reources 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Peter_Olson
United States United States
I am active on Stack Overflow.

You can contact me via email at peter.e.c.olson+codeproject@gmail.com

You may also be interested in...

Comments and Discussions

 
Questionasking your suggestion! Pin
_Dhull 26-May-15 21:44
member _Dhull 26-May-15 21:44 
AnswerRe: asking your suggestion! Pin
Peter_Olson26-May-15 23:11
memberPeter_Olson26-May-15 23:11 
GeneralRe: asking your suggestion! Pin
_Dhull 27-May-15 20:32
member _Dhull 27-May-15 20:32 
QuestionRated 5 -- Question About Delegates (Last Piece) Pin
Matt U.12-Nov-14 3:33
memberMatt U.12-Nov-14 3:33 
AnswerRe: Rated 5 -- Question About Delegates (Last Piece) Pin
Peter_Olson12-Nov-14 6:58
memberPeter_Olson12-Nov-14 6:58 
GeneralRe: Rated 5 -- Question About Delegates (Last Piece) Pin
Matt U.12-Nov-14 7:37
memberMatt U.12-Nov-14 7:37 
Questionnice Pin
ravikhoda4-Feb-14 0:07
professionalravikhoda4-Feb-14 0:07 
GeneralMy vote of 5 Pin
csharpbd8-May-13 0:28
membercsharpbd8-May-13 0:28 
GeneralMy vote of 5 Pin
Rohan M Thomas16-Jan-13 22:45
memberRohan M Thomas16-Jan-13 22:45 
QuestionExcellent Pin
Nitin Sawant6-Dec-12 17:09
memberNitin Sawant6-Dec-12 17:09 
QuestionNice read Pin
HaBiX3-Oct-12 22:29
memberHaBiX3-Oct-12 22:29 
AnswerRe: Nice read Pin
Peter_Olson7-Oct-12 14:26
memberPeter_Olson7-Oct-12 14:26 
GeneralRe: Nice read Pin
jlopez7887-Dec-12 2:55
memberjlopez7887-Dec-12 2:55 
GeneralRe: Nice read Pin
Peter_Olson7-Dec-12 4:20
memberPeter_Olson7-Dec-12 4:20 
GeneralMy vote of 5 Pin
Razibul Islam30-Sep-12 22:40
memberRazibul Islam30-Sep-12 22:40 
GeneralJavascript Variable Arrays Pin
Gary Noter31-May-12 12:24
memberGary Noter31-May-12 12:24 
SuggestionAnother possible pitfall with Ajax Pin
pmaree30-May-12 21:30
memberpmaree30-May-12 21:30 
QuestionExcellent Pin
Sufian Saory28-May-12 22:37
memberSufian Saory28-May-12 22:37 
QuestionExcellent Pin
Member 796747528-May-12 21:37
memberMember 796747528-May-12 21:37 
QuestionMy vote of 5 Pin
Harsh Gandhi28-May-12 20:09
memberHarsh Gandhi28-May-12 20:09 
GeneralMy vote of 5 Pin
flywheel28-May-12 13:37
memberflywheel28-May-12 13:37 
GeneralMy vote of 5 Pin
Michał Zalewski28-May-12 6:47
memberMichał Zalewski28-May-12 6:47 
GeneralMy vote of 5 Pin
strictly8628-May-12 4:15
memberstrictly8628-May-12 4:15 
GeneralMy vote of 5 Pin
_Maxxx_27-May-12 19:17
member_Maxxx_27-May-12 19:17 
GeneralMy vote of 5 Pin
Tim Corey22-May-12 12:18
memberTim Corey22-May-12 12:18 
GeneralExcellent! Pin
Sunasara Imdadhusen16-May-12 2:18
memberSunasara Imdadhusen16-May-12 2:18 
GeneralMy vote of 5 Pin
Monjurul Habib10-May-12 19:26
memberMonjurul Habib10-May-12 19:26 
GeneralMy vote of 5 Pin
itaitai9-May-12 20:52
memberitaitai9-May-12 20:52 
Great tips
GeneralMy vote of 5 Pin
Forogar7-May-12 5:26
memberForogar7-May-12 5:26 
GeneralMy vote of 5 Pin
Member 15334041-May-12 19:55
memberMember 15334041-May-12 19:55 
GeneralVery nice! Pin
Eksith25-Apr-12 0:12
memberEksith25-Apr-12 0:12 
GeneralNice article Pin
Muhammed Yaseen24-Apr-12 18:33
memberMuhammed Yaseen24-Apr-12 18:33 
Questionsmall addition to make Pin
GottZ23-Apr-12 10:19
memberGottZ23-Apr-12 10:19 
Generalgreat Pin
ronzulu20-Apr-12 17:53
memberronzulu20-Apr-12 17:53 
BugSmall typo (?!) Pin
Florian Rappl19-Apr-12 6:42
memberFlorian Rappl19-Apr-12 6:42 
GeneralRe: Small typo (?!) Pin
Peter_Olson19-Apr-12 11:11
memberPeter_Olson19-Apr-12 11:11 
QuestionThanks Pin
Jagz W16-Apr-12 18:23
memberJagz W16-Apr-12 18:23 
QuestionExcellent Pin
akpsi16-Apr-12 15:39
memberakpsi16-Apr-12 15:39 
QuestionGood post. Pin
jlafay16-Apr-12 11:16
memberjlafay16-Apr-12 11:16 
AnswerRe: Good post. Pin
peter_olson16-Apr-12 11:37
memberpeter_olson16-Apr-12 11:37 
GeneralRe: Good post. Pin
jlafay17-Apr-12 3:14
memberjlafay17-Apr-12 3:14 
QuestionNice job! Pin
Member 332085216-Apr-12 10:18
memberMember 332085216-Apr-12 10:18 
QuestionGood aritcle! Pin
Dan, Cao Huy16-Apr-12 5:04
memberDan, Cao Huy16-Apr-12 5:04 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150603.1 | Last Updated 19 Apr 2012
Article Copyright 2012 by Peter_Olson
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid