Animate one Div when the mouse hovers over another

13,434

Solution 1

This should do the trick:


$(document).ready(function(){
    $("#blue-box").hover(function(){
        $('#red-box').stop().animate({'margin-top': '200px'}, 1500);
    }, function(){
        $('#red-box').stop().animate({'margin-top': '50px'}, 1500);
    });
});

It should be noted that this can be done easier with CSS, in case the DOM order of the elements are given, but that solution is not flexible if we separate the DOM elements.

Solution 2

This can also be done without Javascript:

#red-box {
    ...
    transition:margin-top 2s ease-in;
}

#blue-box:hover + #red-box {
    margin-top:200px;
}

Demo

Share:
13,434
Flickdraw
Author by

Flickdraw

Updated on June 04, 2022

Comments

  • Flickdraw
    Flickdraw almost 2 years

    I'm looking to animate one div when the mouse hovers over another div tag elsewhere on the page. As an example...

    CSS

    #blue-box {
    position:absolute;
    margin-left:50px;
    margin-top:50px;
    height:100px;
    width:100px;
    background-color:blue;
    
    }
    
    #red-box {
    position:absolute;
    margin-left:180px;
    margin-top:50px;
    height:100px;
    width:100px;
    background-color:red;
    
    }
    

    HTML

    <div id="blue-box"></div>
    <div id="red-box"></div>
    

    JavaScript

    $(document).ready(function(){
        $('#red-box').animate({'margin-top': '200px'}, 1500);
    });
    

    I've also made a jsFiddle to help.

    How would I get the animation to trigger on the red box, whenever the mouse hovers over the blue box? And reverse the animation when the mouse is moved away from the blue box? Returning the red box to it's starting position.

    Could anyone help me?

  • Alessandro Vendruscolo
    Alessandro Vendruscolo over 12 years
    +1 for providing a CSS3 alternative. Also, I've edited it because you declared the transition property twice.
  • Flickdraw
    Flickdraw over 12 years
    This does not animate the red box when I hover over the blue box, at least not in Firefox anyway.
  • bookcasey
    bookcasey over 12 years
    Flickdraw, you need to use the -moz- vendor prefix for it work in Firefox. Here is an updated demo with all the vendor prefixes.
  • Flickdraw
    Flickdraw over 12 years
    Very nice, +1. How easy would this be to make multi-browser and past browser (IE8 + IE7) friendly?
  • Kishore
    Kishore over 12 years
    ooh sorry i guess i messed up the boxes hover over red box it will animate blue box. and i guess what you want is the other way around.
  • Enrique Moreno Tent
    Enrique Moreno Tent over 8 years
    This is the optimal answer, in case that the div you want to transform is immediately after the one that triggers the effect. Sadly this answer is not very flexible, if the DOM elements are a little more mixed up inside the DOM tree, so it should be taken with great attention to its limitations.