views:

67

answers:

3
$('#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..

A: 

It's the formal parameter for the function. jQuery will pass in an event object when the function is called. This is used to determine the target. As noted in the documentation, jQuery will always pass an event object even when the browser (e.g. IE) doesn't.

In this case, the target tells you which element was originally clicked.

Matthew Flaschen
+5  A: 

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.

Frankie
It is also worth noting this is not specific just to jQuery, but to native events in javascript as well.
balupton
ah, i didn't know it was just a variable... so, what's the purpose of that variable if I'm not using it anywhere else in my script but those 2 places? i don't get what it holds... what tells it the information to hold?
android.nick
@android.nick even though you may not use it explicitly jQuery needs it. Imagine the `click` scenario. jQuery needs to know the action performed and the item the action was performed on. So even if you're not using the variable it's used internally. But you can call `$('#myTable').click(function() { ... });` just as well.
Frankie
A: 

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"&gt;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!

David Hoerster