What is the significant/difference between the following code? (e) at the end
jQuery(document).on( 'click', '.something', function(e) {
vs.
jQuery(document).on( 'click', '.something', function() {
Thanks!
2 Answers 2
There is technically no difference in the 2 expressions. 'e' refers to the event variable which is optional and works more like this expression in jquery. you can use that e variable to figure out certain information like the target which invoked the event or any other property.
jQuery(document).on( 'click', '.something', function() {
alert(this.id); // gives you the id of the element using this
});
jQuery(document).on( 'click', '.something', function(e) {
alert(e.target.id); // gives you the id of the element using event
});
In my opinion, the biggest advantage of using the event e is that it gives you more correct info compared to this when the event handlers are invoked over the document.
$(document).on('click',function()
{
alert($(this).attr("id")); // id as undefined
})
$(document).on('click',function(e)
{
alert(e.target.id); // gets the correct id
})
Example : http://jsfiddle.net/twjwuq92/
Comments
The e parameter is the event triggered, which is the jQuery event object. Both the cases, event is created, but to access it, we are passing it as parameter.
// Case 1
jQuery(document).on( 'click', '.something', function(e) {
e.which; // Short form. This is Click Event object.
});
// Case 2
jQuery(document).on( 'click', '.something', function() {
// There's no reference to the event that's triggered.
});
6 Comments
window.event is a microsoft-specific implementation and not standard.window.event object only exists for IE. It's not correct still.event is not the same object as the one jQuery passes to the callback.ReferenceError: event is not defined in FF.
eventobject to the anonymous function, whereas the second one doesn't. Try logging the variable. See: api.jquery.com/category/events/event-objectename - if accessing such is not required then the parameter can be safely omitted and it will not affect the program. In both cases the supplied argument(s) can be accessed viaarguments.