Fabio Fabio - 6 months ago 18
Javascript Question

jQuery: div moving as it shouldn't .mouseover() .mouseout()

I am new to jQuery, I have this div with an image and text inside: on mouse-over the whole div should move down, and on mouse-leave it should return to its original position. If I trigger the mouse-over on the text it works properly, but if I do the same on the parent div or on the image, the div continues to move up and down.

Here's my HTML:

<div id="sidebar">
<a href="/">
<img src="//path" width="150" style="margin-bottom:5px;" />
</a>
<div id="mydesc"></div>
</div>


And my Javascript:

$('#sidebar').mouseover(function(){
$('#mydesc').animate({
'marginTop':"30"
});
});
$('#sidebar').mouseout(function(){
$('#mydesc').animate({
'marginTop':"0"
});
});

Answer

This should fix things. I've had this problem before. Just use .hover() with 2 functions http://api.jquery.com/hover/. First function is mouseenter and other function is mouseleave. By using this way you less code and easier to keep up. http://jsfiddle.net/9urkfub2/

$(document).ready(function(){


    $("#sidebar").hover(
        function(){
             $('#mydesc').animate({
                'marginTop':"30"
            });
        }, function(){
            $('#mydesc').animate({
                'marginTop':"0"
            });
        });
    });