jQuery event bubbling: Get original element mouseover (for table row highlighting)
It's called event delegation.
You're using jQuery which makes it trivial to find the triggering <tr>
element of the event, via closest
:
$('#myTable').mouseover(function(event) {
var tr = $(event.target).closest('tr');
// do something with the <tr> element...
})
closest
was in fact written to support event delegation like this. It's what live()
uses internally.
Alex
Updated on June 13, 2022Comments
-
Alex about 2 years
I'm trying to reduce my 'onmouseover' event listeners in my table (in which I highlight rows on hover). I want to do this by attaching an event listener to the entire table instead of each <tr> (that's how I have it now). The reason is that IE is reacting very slow and the only answer I found to this was to reduce the number of event listeners.
Sample code:
<table id="myTable"> <tr> <td>Somedata</td> </tr> <tr> <td>Somedata 2</td> </tr> <tr> <td>Somedata 3</td> </tr> </table>
In this scenario, if I hover over the second <tr>, I understand that the "onmouseover" event bubbles from tr to the table.
How could I find out in my jQuery $('#myTable').mouseover event which tr was hovered and change its css class?
Edit: The idea for this comes from this SO question (but unfortunately no source code in the answer): Speeding Up Multiple OnMouseOver Events in IE
-
Alex almost 15 yearsWhat is the "e" parameter used for? Is it necessary & what does it represent?
-
Crescent Fresh almost 15 years@Alex: the
e
parameter is theevent
object generated by themouseover
. Every user action generates one of these events. See quirksmode.org/js/events_properties.html -
Crescent Fresh almost 15 years@Alex: ps I've edited the answer to use a better var name than
"e"
;) -
ssss about 13 yearsCan’t you just use
$(this)
instead of$(event.target)
? -
Jason Suárez over 12 years@Timwi $(this) in this case is equivalent to $('#myTable'); event.target is the lowest element on the chain, so finding the closest <tr> will match the element you want.
-
Pierre about 10 yearsor you could just
$('#myTable tr').mouseover(function(e){ $(e.target); });
-
Gone Coding over 7 years@Pierre: The preference is usually to have a few delegated or bubbling event handlers, rather than loads of individual handlers wired up directly to elements, so that is not a better option than the one shown.
-
Pierre over 7 years@GoneCoding I agree! This was posted a while back before I knew what I know now. Never too old to learn ey!