2

I have html table like this:

<div id="recommendation">
  <table id="category_selected">
    <tr>
      <td>1</td>
    </tr>
  </table>
</div>  

and jquery like this:

$(function()
{
    $("#recommendation tr").mouseenter(function()
    {   
        alert("Yes");
    }
}

and everything works fine. But when I change html of recommendation with this:

$.post("path/script.php", {dataIn: dataInEncoded}, function(data, status)
{
    if(status == 'success')
    {
        $("#recommendation").html(data);
        /*(data exactly the same as default html)
           <table id="category_selected">
             <tr>
               <td>1</td>
             </tr>
           </table>
        */
    }
}

Jquery mouseenter suddenly doesn't work (trigger).

Nivelety
  • 73
  • 1
  • 1
  • 8

4 Answers4

3

The issue is here:

$("#recommendation tr").mouseenter(function(){

this works for static html element, but in your case when you are adding some html dynamically. To deal with dynamic html use jquery on() like:

$(document).on('mouseenter', '#recommendation tr', function(){

and try again.

Mayank Pandeyz
  • 25,704
  • 4
  • 40
  • 59
3

You need to use the delegated ("live") function.

$("body").on("mouseenter","#recommendation tr",function()
{   
    alert("Yes");
}

the event will listen to all the elements, listened in the second parameter, that are present or will be created in the "body" element.

You can anchor the function to the first non-mutable element, for example

$("#recommendation").on("mouseenter","tr",function()
{   
    alert("Yes");
}
Emanuele Parisio
  • 1,192
  • 8
  • 27
0

That's because the DOM doesn't work the way you think it does. You've effectively replaced the innards of that node with new HTML. This means that all of the previous nodes that were children of #recommendation have been removed from the DOM. And since those rows had your event listeners on them, those event listeners have also been removed from the DOM.

What you'll need to do is reattach your event listeners to the DOM after repopulating the table. Copy your code to add the event listeners after you've repopulated the table and see what happens.

Or, as Mayank Pandeyz says, use the jQuery .on function. Then you won't have to reattach.

villecoder
  • 13,323
  • 2
  • 33
  • 52
0
<div id="recommendation">
  <table id="category_selected">
    <tr>
      <td>1</td>
    </tr>
  </table>
</div>  


document.getElementById("category_selected").onmouseover = function() {mouseOver()};
function mouseOver() {
    alert("Yes");
}
Madhumitha
  • 340
  • 5
  • 24
  • Why there is a function inside function? `function() {mouseOver()};`? it could be like `document.getElementById("category_selected").onmouseover = mouseOver;` Anyways, it does not solve the problem. – VPK Apr 11 '17 at 13:19