Writing better jQuery Code

Posted on August 13, 2008

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
http://www.php.net
http://www.asp.net
http://www.ruby-lang.org
http://www.python.org
http://www.adobe.com/products/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.

Leave a Reply

You must be logged in to post a comment.