Writing better jQuery Code
We all know that jQuery is great, that you can do things in 2-3 lines in jQuery that you can in 20 lines of Javascript, but is your jQuery code starting to get a bit bulky? Could you do things better?. I’m going to show you how to reduce a 20-25 line jQuery script into 3 lines by making the script dynamic, and give a few tips on improvement of your code.
What we want: When the user clicks a list item, it will show the corresponding div
- PHP
- ASP
- Ruby
- Python
- AIR
If i were a beginner and i was asked to write the script, i’d most likely code sections for each id/div such as below.. Once the specified link is clicked it’ll hide all the divs shown(the other content panels) and then it’ll fade in the relevant content panel.
$("ul#langs li#php").click(function(){
$("div#container div").hide();
$("div#container div#d_php").fadeIn("slow");
});
$("ul#langs li#asp").click(function(){
$("div#container div").hide();
$("div#container div#d_asp").fadeIn("slow");
});
This is alright.. it does the job but for each id/div you need around 3 lines of code, your also listening for alot of events (all of those clicks) which may use more memory and slow the script down in general.
Instead of listening for unique clicks(php, asp, ruby etc..), why don’t we just listen for any click (on the list) and after its clicked, find out which item it was by getting the id (via attributes), save it as a variable, and then use that variable in the selector for the div.
$("ul#langs li").click(function(){
var elid = $(this).attr('id');
$("div#container div").hide();
$("div#container div#d_" + elid + "").fadeIn("slow");
});
This code is alot smaller, its scalable and its not going to get any bigger. You can use this method in other applications such as calling for ajax.
Questions/Comments?
**The Next Day**
Thanks for all your thanks/comments/”gtfo noob why are you programming”-ings. Matt August, Bryan Migliorisi and Karol Kowalski pointed out that you can’t have more than 1 element with the same id, I completely overlooked this and I’ve fixed the code up.


August 14, 2008
Hi there.
That’s some great article. Of all the jQuery resources that I have collected, it is the only one that actually talks about writing better code.
Thanks.
August 14, 2008
The Complete Guide for You to Become an Almighty jQuery Developer…
Have you ever had to develop something yourself only to find out that there had already been a plugin developed?
Don’t you enjoy dreaming about what you could have on your site and finding the right plugin right away?
Then you should find this lis…
August 14, 2008
Why do you have
$(”div#container div#” + elid + “”)
instead of just
$(”div#container div#” + elid)
?
August 14, 2008
You may want to keep in mind that you should only be using an id once per page. If you were to use something like document.getElementById(”php”) it would only return the first one.
You could change $(”div#container div#” + elid + “”).fadeIn(”slow”); to $(”div#container div#” + elid + “content”).fadeIn(”slow”); and append “content” to all of the div ids.
August 14, 2008
I am pretty sure that both of your methods will be creating individual event listeners for each element found in the selection.
Instead, you should only attach an event listener on the ul only and then on the click event, find out which inner target element was clicked. That is how you would lower the amount of event listeners.
Also, you cant have mutliple elements on a single page share the same ID. This is invalid XHTML
August 14, 2008
This is vary nice good lookup site.
August 14, 2008
You can’t have multiple elements with the same id. If your code works it’s only because of browsers quirks. Also querying $(’element#id’) is slower than actually querying $(’#id’), because the browser needs to parse the DOM searching for all nodes of certain name and only later it can traverse them searching for the #id.
August 14, 2008
You could shrink it even more
$(”ul#langs”).click(function (event) {
var id = $(event.originalTarget).text().toLowerCase();
$(”#container div”)
.hide()
.filter(”#” + id)
.fadeIn(”slow”);
});
(note that you were using same ID twice, for list item and div)
August 14, 2008
thanks this small but focused toturial helped me understand a few things.
August 15, 2008
@Yura, Blancodan, Vish
Thanks alot!
@Joe Grossberg
Both ways work, won’t be a big performance issue.
Thanks for the feedback guys, i’ve updated the first post with better code.
August 15, 2008
[...] Writing Better jQuery Code | Query7 - PHP jQuery Linux (tags: tutorial jquery javascript tutorials) [...]
August 18, 2008
[...] Writing Better jQuery CodeLearn how to write better jQuery code to save your time and enjoy the process. [...]
August 19, 2008
How about the following?
$('#langs li').click(function() {
$("#container div").hide();
var index = $('#langs').index(this);
$("#container div").get(index).fadeIn("slow");
});
It saves you from having to assign so many IDs. This also makes it easier if the HTML is generated by some CMS, so you don’t have to hack the code to output IDs.
Of course, it’ll only work if order of the list of links corresponds exactly to the divs like it is the case in this example.
Note it’s not necessary to prefix your ID with div like “div#container”, if they’re unique (and they must be unique or the HTML is invalid).
August 19, 2008
Eek, the styling is off (code has black letters, but here’s a black background). You can see the code by selecting it.
A ‘preview comment’ function would be nice
August 20, 2008
@Panzer
While both ways work it is just stupid to concatenate an empty string. If you want to add nothing to it why add it? It doesn’t matter if it has a small performance hit in this case if you do it once, you will most definately do it again and if you have several unnecessary string concatenations you are building your way to big performance issues. It is also considered bad practice.
You might also want to take a look on event delegation in jquery:
http://dev.distilldesign.com/log/2008/jan/27/event-delegation-jquery/
http://www.danwebb.net/2008/2/8/event-delegation-made-easy-in-jquery
August 21, 2008
Great tutorial~~
Help me more understand on JQuery as a beginner.
Thanks a lot!
September 11, 2008
Good Tutorial for a beginner like me.
I would be great if we discuss on all UI Components in Jquery like this.
Thanks a lot guys .Especially to Peter Bex for giving a much clean way…
September 15, 2008
great tutorial but has been better that have a live demo.
Good luck.
September 18, 2008
Great Tutorial for a beginner like me .
Thanks a lot!
October 13, 2008
hi, great tu, thanks! but one question: how do i solve the problem to have just one unique id… cheers!
October 16, 2008
Thanks for this tutorial. Thanks to Peter Bex for his great comments.