3

First I am dynamically writing a table to a div using innerHTML and then I'm trying to get a jQuery function to run when a user hovers a table cell. The jQuery function fires on a table that exists in the HTML, but once I overwrite the innerHTML with a new table, jQuery doesn't run the function on hover anymore.

<div id="replaceThis">
    <table id="myTable">
        <tr><td class="myCell">Help</td></tr>
    </table>
</div>

Then I use .on('mousenter') to run a function

$('#myTable tr td.myCell').on('mouseenter',function(){alert('omg help'); }

This all works fine until I replace the innerHTML of the div with a new table, much bigger, that is created with a loop through some data. The jQuery then does not fire the function on the mouseenter even though the id's and classes are the same.

Praveen Reddy
  • 7,295
  • 2
  • 21
  • 43
bocamp
  • 33
  • 2

2 Answers2

3

Use delegated events. When you replace the body, it generates new HTML elements, which do not have your event handler attached anymore.

jQuery provides the delegated handler feature with the selector parameter on the on function.

For instance:

$('body').on('mouseenter', '#myTable tr td.myCell', function(){alert('omg help'); }

Read the Direct and Delegated Events paragraph in the docs: http://api.jquery.com/on/

Lucas Trzesniewski
  • 50,214
  • 11
  • 107
  • 158
1

After the DOM element is overwritten the events are no longer attached to the DOM element. Using Delegated events will solve your problem.

$('#myTable tr td.myCell').on('mouseenter',function(){alert('omg help'); }

$('#replaceThis').on('mouseenter', "#myTable tr td.myCell", function () {
    alert('omg help');
});
Praveen Reddy
  • 7,295
  • 2
  • 21
  • 43