10 Useful jQuery Techniques to Improve Your Code

May 14, 2013 · 35 comments

by Lars


jQuery is known for making JavaScript things that used to be hard or almost impossible for most people simple and elegant. While the jQuery community is growing so is the number of plugins available for anyone to address nearly any client side need.

“Problem” is that using jQuery this way is so simple that getting to know the framework well is not really needed. Most people simply download a plugin and set it up according to the documentation. A good example of this is the many website using jQuery sliders today. The sliders are simply all over the place and there are plenty of cool plugins to choose from. Still I believe jQuery is worth investigating further and web every front-end developer and designer would benefit from knowing a bit more of what is going on under the shiny surface. This post will show you jQuery techniques and give you some insight and inspiration that you may use going forward.

If you find this post useful I will recommend that you take a look at these previous posts:



#1 – Load the jQuery framework from Google or jquery.com

This is a tip you see in most jQuery pospts but it can’t hurt to repeat it. Google have been hosting several JavaScript libraries for a while now on Google Code and you may want to load it from them instead of from your server to take advantage of their great bandwith.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"

You can actually also load the latest jQuery version from jquery.com using this code:

<script src="http://code.jquery.com/jquery-latest.js"></script>

#2 How to make sure an image has loaded properly

You can do this by using the .load() method on an “img” element and put a callback function in it. In the example below the “src” attribute of an image tag is changed to load a new image and attaches a simple load function. This technique can fx. be useful when building a captcha form validator.

$('#myImage').attr('src', 'image.jpg').load(function() {
 alert('Image Loaded');
 //perform action that is dependant of image being fully loaded

#3 Easy Vertical Align

If you need to center an element to the documents height this jQuery snippet will be very useful. Using it is very simple as all you need to do is to add the class verticalcenter to the object that you want to center to your document. In the example below “TESTER” will be moved when “Do it” is clicked.

<div onclick="var doc_height = $(document).height();
  var el_height = $('.verticalcenter').height();
  $('.verticalcenter').css({'position' : 'relative' , 'top' :
  doc_height/2 - el_height/2});">Do it</div>
<div id="test2" class="verticalcenter">TESTER</div>;

#4 Replace a <div> with jQuery

A simple and possibly the most simple way is to use the replaceWith method.

$('#targetdiv').replaceWith('<div>going to be inserted!</div>');

#5 manipulate text with Regular Expressions and jQuery

You can perform quite power full actions with text by using regular expressions Regex. jQuery support Regex in a simple way and if you know Regex you will pick this up fast. Here is an example where the word “test” is removed from text in an element on the page. If you need to read up on Regex you may want to read this post.

<div onclick="var element = $('#test2'); element.html(element.html().replace(/\s+test/gi, ''));">Do it</div>
<div id="test2">Remove it: test</div>

#6 Opening links in new a window based on class or attribute

This jQuery technique is a simple and quick way to make all your external links open in new browser window. In order to make the code below work you need to add the attribute rel=”external” to your external links.

Another advantage of this trick is that target=”blank” attribute is not valid XHTML 1.0 Strict. If you are using the following code, you can achieve the same functionality without having validation problems.

$("a[@rel~='external']").click( function() {
    window.open( $(this).attr('href') );
    return false;

Another way to control this and taking it a bit further by setting window size is shown below. Use the code by setting a class “popupwindow” on a link.

$('a.popupwindow').live('click', function(){
 if (window.focus) {newwindow.focus()}
 return false;

To open a link only as a tab you can use this code (requires a browser that support tabs). Use the code by setting a class “newtab” on a link.

jQuery('a.newTab').live('click', function(){
jQuery(this).target = "_blank";
return false;

#7 Verify if an Element is empty

This is a simple way to test in jQuery if an element is empty. The code will print “Yes (?)” in an alert box because div #test is as empty as it can be.

<div onclick="alert($('#test').html() ? 'Certainly not' : 'Yes (?)');">Test it: Is target element empty?</div>
<div id="test"/>

#8 Simple but useful way to get the number of elements returned by a selector

This will return the number of matched elements. It’s simple and clean and typical for jQuery:


#9 Disable right-click contextual menu

There are a lot of examples and scripts in javascript covering this topic, but also this time jQuery makes you life much easier!:

    return false;

#10 Parsing XML with jQuery (will be useful for AJAX operations)

XML is an important part of AJAX and AJAX is an important part of front end development. With jQuery, when you receive XML from a callback, you’re not actually getting raw text, you’re actually getting a DOM (document object model) that jQuery can traverse very quickly and efficiently to give you the data you need.

Lets take a look at some jQuery that will request a XML document on the server.

    type: "GET",
    url: "test_jquery_xml.xml",
    dataType: "xml",
    success: parseXml

Assuming you have the file “test_jquery_xml.xml” on the server you are ready to start parsing the XML. Lets assume the xml retrived looks like this:

<?xml version="1.0" encoding="utf-8" ?>
<note type="public">
    <body>Just a simple note!</body>
<note type="private">
<to>someone else</to>
    <from>another one</from>
    <body>Just another simple note!</body>

Accessing the xml data is simple and elegantly achieved in jQuery as show below.

function parseXml(xml) {
 //find every note and print the type
   $("#output").append($(this).attr("type") + "<br />");

Output will be:

{ 18 comments… read them below or add one }

Mani Viswanathan December 22, 2011 at 10:19 am

Some fantastic little tricks. Never thought disabling a context menu will be so short and easy.


prerna October 25, 2011 at 7:05 am

awesom n very great.keep it up …


Uterine fibroids causes September 7, 2011 at 8:42 am

A real must for any modern web designer. Thanks!


Fibroids Treatment September 7, 2011 at 8:39 am

That vertical align will come in handy, thanks!


Uterine Fibroids September 7, 2011 at 8:37 am

I need to start covering some more jQuery on my site.


Asif Iqbal December 30, 2010 at 8:59 pm

Awesome stuff.. It is very basic but being made my code better enough.



adam j. sontag December 28, 2009 at 8:38 pm

You should take this post down, or at least correct all the errors and misinformation in it. It is only spreading inaccurate information around the community.


tripwiremag December 28, 2009 at 10:15 pm

@adam, I normally appreciate feedback and react on it ASAP. Unfortunately I really find it hard to address yours. Would you mind giving a few more details on what is not worth being published. I believe you will serve the community well by sharing some of your knowledge…


Jim German December 28, 2009 at 8:38 pm

This is the greatest jQuery posts since 1997


SMiGL December 21, 2009 at 10:03 am

Good collection!


rana December 20, 2009 at 4:58 pm

nice tips for jquery developers. Much appreciated. Thanks for sharing…


Amber Weinberg December 18, 2009 at 8:28 pm

That vertical align will come in handy, thanks!


seutje December 16, 2009 at 7:53 pm

onclick makes baby Resig cry :(
disabling right-click context-menu makes pretty much every1 cry :(
having an invalid document (target=”_blank” in XHTML) during runtime makes W3C cry :(
and I’m pretty sure the load event handler should be bound before changing the src


T. Mike December 16, 2009 at 7:51 pm

Wow, this is a really interesting and unique perspective on technology today! A real must for any modern web designer. Thanks!


Josh December 16, 2009 at 6:46 pm

I’ve been using jQuery more and more in my designs and it’s nice to see people covering everything you can do with it. I need to start covering some more jQuery on my site.


adam j. sontag December 16, 2009 at 6:24 pm

2) .load() callback needs to be bound BEFORE .attr(“src”,newSrc) or the callback may not happen reliably. I just corrected this same error on this post http://www.catswhocode.com/blog/10-jquery-snippets-for-efficient-developers, which had the same example.

3,5,7) What’s with giving people examples of ugly inline event handlers? This is supposedly a list of techniques that will ‘improve your code.’

6) @ in attribute selectors was deprecated in jQuery 1.3 and will break your code. This exact same example was in the catswhocode.com blog post as well.

7) You want to check if an element is empty? How about $(elem).is(“:empty”)?

8) .size()? Nothing against its use, but most people tend to go with .length

10) Strangely enough, the final tip in both posts is about parsing XML in jQuery, and how it like, exists and stuff.


Leo L December 16, 2009 at 4:31 am

Hi, nice triks.
I think in the last example it should be .attr(“type”)


tripwiremag December 16, 2009 at 6:45 am

@Leo, Thanks for the feedback and the correction.


Leave a Reply

Your email address will not be published. Required fields are marked *

{ 17 trackbacks }

Previous post:

Next post:

Web Analytics