8

I'm having a problem with dynamically created elements on hover state. When I hover on newly created html element, it doesn't work.

Here's my HTML code:

<button id="create">create new button</button>
<button class="hover">hover me</button>
<div></div>

jQuery:

var createBtn = $("#create");

createBtn.click(function() {
    $('div').append('<button class="hover">new hover button</button');  
    return false;        
}); 


$('.hover').hover(function() {
    alert('you hovered the button!');
}, function() {
    alert('you removed the hover from button!');
});

I even tried this code:

$('.hover').on({
    mouseenter : function() {
         alert('you hovered the button!');
    },
    mouseleave : function() {
        alert('you removed the hover from button!');
    }

});

as shown here http://api.jquery.com/on/, but still no luck. Here's also demo: http://jsfiddle.net/BQ2FA/

Lado Lomidze
  • 1,503
  • 5
  • 19
  • 32
  • maybe this will help about on/off: http://stackoverflow.com/questions/11283341/jquery-disable-click-until-animation-is-fully-complete – Barlas Apaydin Jul 18 '12 at 12:51

2 Answers2

18

This isn't the correct syntax.

Use this to listen to your events for dynamically created '.hover' elements :

$(document).on('mouseenter', '.hover',  function(){
         alert('you hovered the button!');
}).on('mouseleave', '.hover', function() {
        alert('you removed the hover from button!');
});
Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
  • 2
    The first argument to `.on()` can still be an object (as the OP is currently doing) if you want to avoid having to explicitly call it multiple times. (Downvote not mine - this answer is still correct). – James Allardice Jul 18 '12 at 12:51
  • @JamesAllardice There are many possible solutions, and I agree it's possible to make shorter, but OP's call couldn't be applicable to dynamically created '.hover' elements, that's what I fixed. – Denys Séguret Jul 18 '12 at 12:54
  • 1
    I know, I was just pointing out the fact that the OP wouldn't have to change that much - they can just change the initial selector and add the `.hover` selector as a second argument after the map of event names and event handlers. They don't have to change it to be 2 separate calls to `.on()`. (The comment was for the benefit of the OP, not a criticism of your answer). – James Allardice Jul 18 '12 at 12:56
  • Yes, that's right. I won't change my code as this is a detail and Esalija already gave this variant but thanks for the precision : it's good to me too (not only OP) to be reminded of the alternate syntaxes. – Denys Séguret Jul 18 '12 at 12:59
3

You are using .on for direct binding, you need to use it for delegation:

$('div').on({
    mouseenter: function() {
        alert('you hovered the button!');
    },
    mouseleave: function() {
        alert('you removed the hover from button!');
    }
}, ".hover");

http://jsfiddle.net/BQ2FA/2/

Esailija
  • 138,174
  • 23
  • 272
  • 326