10 Best Practises for jQuery Beginners

Note: This article has been marked for a quality review and will soon be updated.

jQuery is the one of the most popular JavaScript frameworks available; it enables developers to write code that is easy to understand but that also allows really powerful functionality. There are a boat-load of tutorials out there on jQuery, and the documentation is awesome, but in this article I’ll go over the things that all beginners should know about jQuery.

1) Document.ready

One thing that often catches newbies out is that their code doesn’t seem to be having any effect on their page, despite all of it being correct. A major cause of this is that their jQuery code is attempting to access DOM elements before they exist. This can happen because developers place their JavaScript in the <head> of their pages, and so by the time the rest of the page has loaded jQuery doesn’t know what’s going on. The simple way to solve this issue is by telling jQuery to execute the code only when the DOM has finished loading, like so:

	//Code goes here

But be warned, there are some circumstances where you shouldn’t bother wrapping code in it. For example if you’re clued-up about performance and already have all your code at the bottom of your page, it’s unnecessary to use it, because all the elements already exist. Other exceptions might include wanting better code reusability – say for instance placing non-jQuery functions outside of the wrapping.

2) Cache elements

A lot of the time people write functions like:


And there isn’t anything wrong with that. But if you started doing 10 things to the element once it were clicked it would start to look a little messy. To fix this it’s a good idea to put the $(this) selector into a variable, like so:

	var el = $(this);	

This will give you less code to write in the long run, and using descriptive variable names will also help you keep focus on what you are manipulating. But more important than that is the performance increase – asking jQuery to return an element over and over as we did before wastes valuable performance – so caching will speed up your code!

3) Chaining

And the above brings me nicely to my next point – chaining. You can chain jQuery functions, meaning that you don’t have to separate all those lovely functions, so the code I just wrote could actually look like:


And by just chaining those functions we have condensed 3 lines of code into 1.


One reason why a number of developers like jQuery is because it has an excellent syntax for AJAX. In Javascript making AJAX requests is cumbersome and difficult to learn, but in jQuery it’s pretty easy. So if you’ve taken the time to fade in messages to your users using jQuery, why not go ahead and submit forms using AJAX, thus creating a more cohesive user experience.

This is how it’s done:

	var dataString = $(this).serialize();
		url: 'process.php',
		data: dataString,
		type: 'POST',
		success: function(data){
			//Do something

The above code waits for the form with a class of ‘.myform’ to be submitted, and then sends the data in the form via a POST method to ‘process.php’. If the whole thing works well the success function is called and accepts some data. You would simply set up process.php to either return an error or simply say ‘success’, and then act accordingly – perhaps showing a success balloon or error notification.

5) Using delegate()

Most beginners typically start by using syntax such as:

	//Do something

Just as I did above. There isn’t anything technically wrong with that code, it’s just that it could be better. Newbies will often find them googeling why their click() method doesn’t work on dynamically created elements (as could be done using AJAX), and the reason for this is because jQuery binds the event handlers to the elements when the page is loaded. So we have to change the way we write our code to ensure we don’t run into any issues.

To do that we can use the handy delegate() method. For example:

$('.myWrapper').delegate('p', 'hover', function(){

The code above tells jQuery to listen for hover events on paragraph elements within the .wrapper element. The method allows us to add elements without worrying if event handlers will listen out for changes to them, and so it is good practise to use it in production.

6) Using powerful selectors

Complex selectors in jQuery allow us to tailor more specific and targeted interactions on our websites. Say for instance we want to target all paragraphs, except those with a class of ‘not-me’. A great way to do this is like so:


There we used the :not() syntax to exclude elements with a class of ‘.not-me’ – a simple, but very effective way of selecting only the elements we want. Furthermore we may only wish to select the first paragraph on our page, to do that we would use another handy selector:


There are a bunch of powerful selectors besides just class and ID based ones, you can take a look in the docs over at: http://api.jquery.com/category/selectors/

7) Use callback functions

I often answer questions from people who want to know how they can trigger actions once other actions have finished execution. And the simple answer is by using callbacks. For those new to jQuery the term by be unfamiliar, but you’ve already witnessed one in the AJAX example above! A callback method is one that is called after the method in question has done it wants to do, in jQuery a lot of functions allow you to pass a callback function of your own; let’s take a look at how we’d do this:

	$(this).fadeOut(500, function(){
		alert('Element faded out!');

The code above listens for a click on our elements, fades it out, and then alerts the user about it. The callback function is passed as a separate parameter to our fadeOut() method, and is executed after the element is faded-out.

8 ) Use a context

In the interests of performance let’s take a moment to think about how jQuery finds elements. When you say something like:

$('.myelement').click(function(){  });

jQuery searches the entire DOM for it. But what if you only have things with that class within say a div with a class of ‘.main-content’? If so you can provide a context to jQuery (much like we did with the delegate() method above). Doing this enables jQuery to only search within that context, thus saving on performance. And here’s how it would look:

var context = $('.main-content');

$('.myelement', context).click(function(){

The more specific (and smaller) your context, the faster your code.

9) Pass objects not identifiers

When writing your own functions it might seem like a good idea to do something like:

function myfunction(id){


But that really isn’t very flexible. It’s far better to actually pass the object around like so:

function myfunction(el){


10) Don’t depend on jQuery

While the techniques above are good advice for writing solid jQuery, you certainly shouldn’t depend on the thing. Never use jQuery as a replacement for CSS – not only is it more inefficient, but you are ignoring users without Javascript turned on, and it’s a sure fire way to annoy users.





One response to “10 Best Practises for jQuery Beginners”

  1. Karthik avatar

    Very Good Article!!!!!!!!!