Using the .on() method in jQuery
The .on() method in jQuery is used to bind event handler functions with a selector or selectors, like so:
$('#selector').on('click', function() {
// stuff that executes when the event occurs
});
The same outcome can also be achieved by writing the statement like this:
$('#selector').click(function(){ // stuff that executes when the event occurs });
It might seem like the second method is preferable, as it looks more efficient and dry. However, using the .on() function instead is actually much more versatile for a couple of reasons.
It lets you pass additional data to the handler.
For a given selection, it allows you to bind multiple events.
PASSING DATA TO THE EVENT
You may want to pass data to an event handler function so that the action can vary in different circumstances. You can do this by specifying an extra argument in the 'on' method. When you pass data like this, it is stored in the event object, which is passed as an argument to the event handler function. For example:
var myData = { message: 'You clicked on a button' };
$('button').on('click', myData, function(event) {
alert(event.data.message); // 'You clicked on a button' will be displayed.
});
In this example, myData is the variable that holds the data I want to pass. I pass it in as the second argument of the on method. This data will be stored in the event object (which exists for every event, but is not always explicitly stated). In order for me to access my data in the function, I'll need to pass the event object to the function (written above as 'event').
Then, I can access data from the event object with the data property.
Calling event.data will return the entire myData object, and called event.data.message will return the value for that property, which in this case is 'You clicked on a button'.
BINDING MULTIPLE EVENTS TO A SINGLE SELECTOR
Another cool thing you can do with the on method, that you can't with specific event functions is specify multiple events for a single selector. Let's say you want different things to happen when you mouseover a selector versus when you click on it.
To do this, you would write it in a slightly different format, like so:
$('button').on({
'click' : function(){
// do something interesting
}, // end click function
'mouseover' : function() {
// do something else
} // end mouseover function
});
Here, the events are wrapped in an object literal and separated by commas. For each event handler, the name of the event is the property and the function is the value.