0

I have a dynamic HTML content

<div id="parent">
    <div class="child">
        Hover Text
    </div>
</div>

when I try to hover "hover text" inside child element with this code it doesn't work.

$("#parent").on('hover', '.child', function()
{
    alert("Hello");
});

this code neither

$('#parent').on('hover', '.child', function(e) {
    ...
});

I use jq vs 1.10.2

FreshPro
  • 875
  • 3
  • 14
  • 35
Samy Reef
  • 73
  • 1
  • 9
  • possible duplicate of [How to make jQuery 1.7 .on() hover?](http://stackoverflow.com/questions/11541754/how-to-make-jquery-1-7-on-hover) and http://stackoverflow.com/questions/9827095/is-it-possible-to-use-jquery-on-and-hover – j08691 Jan 07 '14 at 18:37
  • thank you, that's helpful ! – Samy Reef Jan 07 '14 at 18:45

3 Answers3

3

If the entire div#parent block is dynamically generated, you may need to bind your hover listener to the document itself, as shown below.

Also, I suggest using mouseenter and mouseleave listeners, as the hover shorthand was removed in jQuery 1.9.

Deprecated in jQuery 1.8, removed in 1.9: The name "hover" used as a shorthand for the string "mouseenter mouseleave".

Here's my sample:

jQuery(document).on('mouseenter', '#parent .child', function (e) {
    jQuery(this).css('backgroundColor','#F00');
}).on('mouseleave', '#parent .child', function (e) {
    jQuery(this).css('backgroundColor','#FFF');
});

http://jsfiddle.net/UX8z5/1/

showdev
  • 28,454
  • 37
  • 55
  • 73
0

try adding mouseenter and mouseleave events with on(). Here is example:

$(function(){
    $("#parent").on({
        mouseenter : function(e){
            alert("Mouse enter");
        },
        mouseleave : function(e){
            alert("Mouse leave");
        }
    }, ".child");
});

jsfiddle: http://jsfiddle.net/ashishanexpert/2XG9j/

Ashish Kumar
  • 2,991
  • 3
  • 18
  • 27
0

You can use .hover() method binds handlers for both mouseenter and mouseleave events. You can use it to simply apply behavior to an element during the time the mouse is within the element.

$(document).ready(function(){
   $('#parent .child').hover(function(){
    alert("Hello");
   });
});

Try in .hover() in Jsfiddle

You can also use .mouseover() event.

$(document).on('mouseover', '#parent .child', function(){
    alert("Hello");
});

Try mouseover event handler fiddle

But here the best practice is bind mouseenter and mouseleave events with event delegation.

$(document).ready(function(){
    $('#parent').on({
        mouseenter: function() {
            alert('Hello');
        },
        mouseleave: function() {
            alert('bye..!!!');
        }
    }, ".child");
});

Try in fiddle

Ishan Jain
  • 8,063
  • 9
  • 48
  • 75