jQuery .on() – How to use it with $(this)

I’m posting this as IĀ foundĀ this particular jQuery method quite difficult to understand from the official documentation at jquery.com. Documentation on the use of $(this) with .on() is not easy to find at the time of writing.

‘Normal’ selectors for events

jQuery selectors are used to select page elements which belong to the DOM (Document Object Model), or, more simply, they are part of the page’s HTML. If you try to select an element which is not in the original HTML or has been added by JavaScript then selecting these in the normal way won’t work.

For example, if you want a button click event you’d normally just use:

HTML

<input id=”continue” type=”button” value=”Continue” />

jQuery

$(document).ready(){

$(“#continue”).click(function(){
// your code
});

});

However, if the button was created in JavaScript but not added to the DOM* then this would not work.

.live()

The original way around this was to use a jQuery method called .live(), which worked by selecting an element and giving it an event. Here are a couple of examples:

$(“#continue”).live(“click”, function(){
// your code
});
$(“select”).live(“change”, function(){
// your code
});

This is quite straightforward to understand. You use the selector in the normal way and just put the event name inside the .live() event. Whilst using .live() currently still works (legacy support) there’s no guarantee it will continue to be supported in the future.

.on()

jQuery has found a far more efficient way of handling this with .on() but there’s a little more to it. Here’s an example of the syntax:

$(“li”).on(“click”, “a”, function(){
// your code
});

Here we have an initial selection “li”, an event “click” and a second selection “a”. The function (your code) will fire when a link (a) within a list item (li) is clicked. The first selector gives the context, the second is the actual selection. By using this first context selector it cuts down the search for the second and makes the whole thing run much faster.

If there is no obvious context element then you can go back to the top level by using $(document) like this:

$(document).on(“click”, “p”, function(){
// your code
});

The important point here, which catches out many people is that the first context selector must be part of the DOM.

.on() and $(this)

In the following code example, if you used $(this) in your code then it would refer to the “a”, rather than the “li” as you might expect.

$(“li”).on(“click”, “a”, function(){
// your code
});

* The easiest way of adding a newly created element to the DOM is by using .append() or .appendTo().

About Chris Smith

Web developer specialising in frontend UI design @chris22smith
This entry was posted in JavaScript, jQuery, on() and tagged , , , , , , , , , , , . Bookmark the permalink.