$('#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..
In jQuery e short for event , the current event object. It's usually passed as a parameter for the event function to be fired.
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.
Using e is just a short for event . You can pass any variable name you desire.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With