Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery/javascript: function(e){.... what is e? why is it needed? what does it actually do/accomplish?

$('#myTable').click(function(e) {     var clicked = $(e.target);     clicked.css('background', 'red'); }); 

Can someone explain this to me, and explain why e is needed, and what it actually does..

like image 862
android.nick Avatar asked Aug 21 '10 02:08

android.nick


People also ask

What is e in function jQuery?

In jQuery e short for event , the current event object. It's usually passed as a parameter for the event function to be fired.

What is e in Javascript function?

The parameter (e) is automatically passed from javascript to you function when you add an event listener. It represents the element that was affected, an example would be the button element that was clicked.

What is variable e in Javascript?

Using e is just a short for event . You can pass any variable name you desire.


2 Answers

Using e is just a short for event. You can pass any variable name you desire.

// would work just the same $('#myTable').click(function(anyothername) {     var clicked = $(anyothername.target); }); 

You can check out more on jQuery's handling of events.

like image 125
Frankie Avatar answered Sep 18 '22 15:09

Frankie


One benefit to having e (the object that raised the event) allows you to prevent the propagation of default behaviors for certain elements. For example:

<a id="navLink" href="http://mysite/someOtherPage.htm">Click For Info</a> 

renders a link that the user can click. If a user has JavaScript disabled (why? I dunno), you want the user to navigate to someOtherPage.htm when they click the link. But if they have JavaScript enabled, then you want to display a modal dialog and not navigate away from the page. You would handle this by preventing the default behavior of the anchor/link and displaying the modal as such:

$("#navLink").click(function(e) {   e.preventDefault();  //this prevents the user from navigating to the someOtherPage.htm   $("#hiddenDiv").dialog({     //options   });  //show the dialog }); 

So having that parameter available allows you to, among other things described in other answers, prevent the default behavior of the selected element.

Hope this helps!

like image 30
David Hoerster Avatar answered Sep 18 '22 15:09

David Hoerster