简体   繁体   中英

Animating a div when hovered

I have a navigation bar that sticks out a little bit from the right edge of the screen. I want it so when you hover on the div, it slides left 550px out of the right side of the browser. I'm using jquery's animate function and I got it to animate properly when hovered, but I can't get it to slide back to the right when you stop hovering on it.

I'm very new to javascript/jquery and I feel like I'm missing something simple...

$(document).ready(function(){
$("#nav").hover(function() {
    $(this).animate({ 
    right: "0px",
    }, 800 );

    (function() {
    $(this).animate({ 
    right: "-550px",
  }, 800 );

});
});
});

And here's #nav's css:

#nav {
position: absolute;
right: -550px;
min-width: 300px;
top: 10px;
height: 50px;
background-color: #B30431;
}

The code has some syntax errors. The code should be :

$(document).ready(function(){
    $("#nav").hover(
        function() {
            $(this).animate({ right: "0px" }, 800 );
        },
        function() {
            $(this).animate({ right: "-550px" }, 800);
        }
    });
});

Good Luck !!

You have made your hover function complicated, you have wrapped the function with () and your function is not executed.

$(document).ready(function() {
    $("#nav").hover(function() {
        $(this).animate({ right: "0px" }, 800);
    }, function() {
        $(this).animate({ right: "-550px" }, 800);
    });
});​

One option, which we use a lot for our animation, is to make a css class that contains that animation, and then ise the .addClass() method to trigger the animation. Its fast, and its browser compatible. You could also use pure css for this.

You could try this... Demo

$(document).ready(function(){

    $("#nav").mouseover(function(){

        $(this).delay(200).animate({right: "0px"}, 800 ); 
        // Added a 200ms delay to prevent quick accidental mouse overs triggering animation.

    });

    $("#nav").mouseout(function(){

        $(this).clearQueue();
        // Gives the user the ability to cancel the animation by moving the mouse away

        $(this).animate({right: "-550px"}, 800 );

    });

});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM