chris
chris

Reputation: 11

jQuery animate on hover, instantly disappear on mouseout?

Hi I have the following code on my website, which causes a div to slide out from the left. This works fine, but when the mouse leaves the area I want to the div to instantly disappear, instead of animating back left again. I have tried many different ways of doing this but none seem to work. I'm sure there is an easy way of doing this. Thanks :)

$(document).ready(function(){
    $("#side-nav a").hover(function(){
        $text = $(this).html();
        $text = "#" + $text + "-box";
        $($text).animate({width:'toggle'},450);
    });
});

Upvotes: 1

Views: 1107

Answers (1)

Nick Craver
Nick Craver

Reputation: 630409

.hover() takes a second method for the mouseleave portion (woth one function, it runs on both mouseenter and mouseleave, like this:

$(function(){
  $("#side-nav a").hover(function(){
    $("#" + $(this).html() + "-box").animate({width:'toggle'},450);
  }, function() {
    $("#" + $(this).html() + "-box").animate({width:'toggle'},0);
  });
});

You can give it a try here, this allows you to still use toggle, but an 0 duration triggers an instant css change, rather than an animation. I would consider though, instead of using the HTML, use the anchors link, like this:

<a href="#MyDiv">

Then your code is much simpler, like this:

$(function(){
  $("#side-nav a").hover(function(){
    $(this.hash).animate({width:'toggle'},450);
  }, function() {
    $(this.hash).animate({width:'toggle'},0);
  });
});

You're using the href="#id" as an #ID selector directly, and if you're also hiding the other element it's pointing at via JavaScript, it means users without JS are much better supported, this will degrade gracefully without hiding content.

Upvotes: 1

Related Questions