avdnowhere
avdnowhere

Reputation: 177

How to add an event handler on .clone element

I have a table row, which is clone from the parent..

Here is the code:

$(this).closest("tr").clone(true).off().attr("class", "newclass").appendTo("#comparelist");

and I also add this code:

  $(".newclass").hover(function () {
        alert("hello");
    });

The table row has been clone successfully, but it can't trigger the hover function..

Does anyone know why this is happen?

Thank You..

Upvotes: 0

Views: 599

Answers (3)

Ashish Kumar
Ashish Kumar

Reputation: 3039

You need to delegate the event on that element, because that was created dynamically. So you can use live, deligate or on event binding methods. I recommend to use on method.

Here is the example.

$(document).on("mouseenter", ".newclass", function () {
    alert("hello");
});

Good Luck!

Upvotes: 1

adeneo
adeneo

Reputation: 318182

Use delegated event handlers

$("#comparelist").on({
   mouseenter : function () {
       alert("mouse entered");
   },
   mouseleave : function () {
       alert("mouse left");
   }
}, ".newclass");

and remove off()

var clone = $(this).closest("tr").clone(true);

clone.attr("class", "newclass");
clone.appendTo("#comparelist");

Upvotes: 4

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35963

try this:

    $(document).on('hover', '.newclass', function () {
        alert("hello");
    });

Upvotes: 1

Related Questions