tuscan88
tuscan88

Reputation: 5829

jQuery get child element that the mouse is currently hovering over

Hi I've got something like the following HTML:

<div class="container">
    <img src="first.png" />
    <img src="second.png" />
    <img src="third.png" />
</div>

I wanna set up a hover event on the container. So that when I hover over the container it will tell me which image inside that container is currently being hovered. Is there a way to do this? I know I can do a hover event on the images instead like $(".container img").hover() but that wont work for what I need to do. so it needs to work from the hover event on the container.

Upvotes: 2

Views: 7766

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388316

I've created a sample using jsfiddle, can you check whether it is what you want.

$(".container").on("hover", "img", function(e){
    var $target = $(e.currentTarget);
    $out.html($target.attr("src"));
})

Upvotes: 3

Brent Anderson
Brent Anderson

Reputation: 966

Use 'mouseover'. An example: http://jsfiddle.net/d4gMS/

$('#container').on('mouseover', function(ev) {
    var src = ev.originalEvent.srcElement;
    if (src.id !== 'container') {
        $('#out').html('hovering ' + ev.originalEvent.srcElement.id);
    }
});​

Upvotes: 0

deadrunk
deadrunk

Reputation: 14125

Try this. Divs instead of images, so it was easier for me to test. :)

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
   "http://www.w3.org/TR/html4/strict.dtd">

<html lang="en">
<head>
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
    <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {
            $('div').hover(function() {
                $('#out').html($(this).attr('tag'));
            })
        });
    </script>
    <style type="text/css" media="screen">
        div { height: 40px; margin: 10px; border: 2px solid #ddd; }
    </style>
</head>
<body>
<div id="name1" tag="one">hey</div>
<div id="name2" tag="two">hey2</div>
<div id="name3" tag="three">hey3</div>
<div id="name4" tag="four">hey4</div>
<p id="out"></p>
</body>
</html>

Upvotes: 0

Related Questions