Search code examples
jqueryeventsevent-bubbling

handle jquery event bubbling on table cell hover


I have just started on event bubbling in jQuery so my understanding is very limited. I have a requirement to handle all the events that happen on the html table (grid) row/cells on parent container level. Example: 1. when the user click on a row, I want instead of binding click event to each I bind it to the parent . 2. when user hover over a cell, I want to show the tooltip i.e. need to set the title attribute to the text element of the cell. I need to bubble this event too.

I am able to solve the first part of my requirement. Here is the code for part 1 (jsFiddle added below):

$('#grid').click(function(evt) {
    var row = $(evt.target).parent('tr'); // Get the parent row
    var cell= $(evt.target); //Get the cell
    alert('Row data: ' + row.text());
    alert('Cell data: ' + cell.text());
});

I thought it would be simple to implement hover too. But I am not able to trap the individual cell value. Here is my sample code in fiddle jsFiddle: sample code to bubble the event on cell hover

also, I noticed that I see alert twice on hover. I guess it is raising the event once for the cell and then for the row/table. Not sure?


Solution

  • You can $.on to achieve this like following. As of jQuery 1.7 all calls to .live(), .bind(), '.delegate()' uses .on() under the hood. And .on binds the event only on #grid and intercept the event on that element and then check if the target mactches the second selector. If so then execute the function.

    $('#grid').on('mouseenter','td', function(){
           console.log($(this).text());
       });​
    

    Working Fiddle