Search code examples
jquerymouseenter

jQuery event not firing on after DOM element is overwritten


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.


Solution

  • 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/