jquery_logo

3 jQuery Shortcuts to Remember

Even developers familiar with jQuery can get confused with the myriad of shortcuts available. There are many variations of doing the same thing which provides great flexibility for developers but can be confusing. All these variations can end-up throwing you off course, which can end up being frustrating when you’re looking for a simple answer to complete some development tasks.

Anyway, here are 3 shortcuts that I consider “must have” jQuery knowledge, so note them down… I know I have!

First of all remember that the jQuery docs will help you get what you need. Always refer there first.

1. Using $ as a shortcut for “jQuery”

Not sure you can call this a shortcut but it is important to know, jQuery uses “$” as a shortcut for “jQuery”. Not really a problem unless you are mixing your libraries. See how you can override this.

2. Document ready function

Probably the most frequent function you use is the document ready function:


$
(document).ready(function(){
...
});

Which can also be represented by:
$(function(){
...
});

Nice shortcut, right? One warning here, as this StackOverflow post suggests, is the more code you have (and more on-ready events) the harder it will be to find them if you use the short form. So use this with caution and realize it’s not that scalable.
3. Click Handler

Another confusion I always have had is with the click handler. There are several ways to do this:


$('#selector').bind("click", function(){
...
})

Or the jQuery 1.7+ version and preferred option is:

$('#selector').on('click', function(){
...
})

In fact .on() should be used instead of .bind(), .delegate() and .live(). Either of these two can be replaced by the short version:

$('#selector').click(function(){
...
})

More details on the click event can be found here. Nothing earth shattering here and it is well documented but it has helped me better understand jQuery especially when I’m reading another person’s code.

Those are my 3 must-have shortcuts, what are yours? Add a comment, let me know what else I’ve missed that you have run into often, I’m sure there are a tonne more.

Avatar photo
Alen Zukich
alen@camcloud.com
No Comments

Post A Comment

Ready to get started with Camcloud?
Find out how easy it is.