A.T. A.T. - 4 months ago 23
jQuery Question

How can i add event to mouse-in mouse out for dynamic DOM element

I manage mouse-over and mouse-out for DOM elements,

$(".selector").hover(function(){
console.log('in');
},function(){
console.log('out');
});


But it doesn't work for dynamic content, how can i do same for dynamic elements.

Answer

You can use the .on() method. Nnote that hover is a shorthand for mouseenter and mouseleave events and not mouseover and mouseout events.

Also, performance-wise, it would be better to select a closing static parent element instead of the document object.

$(document).on({
    mouseenter: function() {
       console.log('in');
    },
    mouseleave: function() {
       console.log('out');
    }
}, '.selector');