Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between function(e) and function()

Tags:

jquery

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!

like image 894
Emily Turcato Avatar asked Nov 22 '25 06:11

Emily Turcato


1 Answers

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/

like image 77
DinoMyte Avatar answered Nov 23 '25 23:11

DinoMyte