0

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.

Ahmed Salman Tahir
  • 1,751
  • 1
  • 17
  • 26
A.T.
  • 18,248
  • 7
  • 39
  • 59
  • dynamic elements means you are getting them by ajax or something like that?? – Vikas Arora Jan 10 '14 at 12:51
  • possible duplicate of [Event binding on dynamically created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – A. Wolff Jan 10 '14 at 12:56
  • no am using plugin, which create elements from json object, in hidden field – A.T. Jan 10 '14 at 12:58

3 Answers3

6

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');
undefined
  • 136,817
  • 15
  • 158
  • 186
1
$(document).on("mouseleave", ".selector", function(){
   //code here
});

$(document).on("mouseenter", ".selector", function(){
   //code here
});

The on function will attach an event handler that listens for the specified event (first argument) on the selected object. When the event is fired and bubbles to the selected element (document in our case), it checks if the target element matches the second argument (the selector). If the target matches the function supplied is fired. In my example I select document however you should select the closest non dynamic parent available for better performance.

Kevin Bowersox
  • 88,138
  • 17
  • 142
  • 176
-2
$(".selector").mouseover(function(){
    console.log('in');
});

$(".selector").mouseleave(function(){
    console.log('in');
});
Bharat soni
  • 2,448
  • 15
  • 27
  • 1
    The OP asked about elements dynamically placed on the DOM are you sure this will work? – Kevin Bowersox Jan 10 '14 at 12:58
  • 1
    **HINT** Dynamically placed – Kevin Bowersox Jan 10 '14 at 13:16
  • Here is what I'm getting at. If the elements already exist on the `DOM` your code will work fine. But if they don't exist the event handler will not be fired because the event does not get attached. That is where `on` comes in. When `on` is used with a selector specified, the event handler will be attached to elements added to the `DOM`, for instance with jQuery's `append` method. My code handles that scenario because it uses `on`, the code you have posted will not handle `dynamic` html elements. If your familiar with the `live` function (don't use) its the same principle. – Kevin Bowersox Jan 10 '14 at 13:25