Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery event bubbling: Get original element mouseover (for table row highlighting)

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

like image 704
Alex Avatar asked Mar 01 '23 06:03

Alex


1 Answers

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.

like image 190
Crescent Fresh Avatar answered Mar 03 '23 08:03

Crescent Fresh