Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected behavior of jquery animation

So I made this animated sidebar:

HTML

<div class="sidebar">
    <div class="block"><a class="link" href="#link1">Menu Option 1</</div>
    <div class="block">Menu Option 2</div>
    <div class="block">Menu Option 3</div>
    <div class="block">Menu Option 4</div>
</div>

CSS

.sidebar{
    position:fixed;
    height:100%;
    width:200px; 
    top:0;
    left:0;
    z-index: 100;
}

.block{
    width:5%;
    height: 20px;
    border-style: solid;
    border-width: 1px;
    text-indent: 100%;
    text-align: right;
    white-space: nowrap;
    overflow: hidden;
    background-color: red;
    padding: 10px;
}

.link{
    text-indent: 100%;
    text-align: right;
    white-space: nowrap;
    width:100%;
    height: 100%;
}

#slider {
    border:1.5px solid black;
    width:10px;
    position:fixed;
}

jQuery

//Sidbar Animations
$(".block").mouseover(function() {
  $(this)
    .animate({
      width: "90%"
    }, {
      queue: false,
      duration: 400
    }).css("text-indent", "0");
});
$(".block").mouseout(function() {
  $(this)
    .animate({
      width: "5%"
    }, {
      queue: false,
      duration: 500
    }).css("text-indent", "100%");
});

And It kinda works, but not exactly as expected. So If I add link inside the div, it still gets animated, but sometimes animation breaks and div collapses, and it's getting hard to actually click the link.

JSFiddle: http://jsfiddle.net/znxygpdw/

How can I prevent this?

like image 994
Tachi Avatar asked Mar 16 '23 19:03

Tachi


2 Answers

In this case is better to use hover function:

//Sidbar Animations
$(".block").hover(function() {
    $(this)
    .animate({
        width: "90%"
    }, {
        queue: false,
        duration: 400
    }).css("text-indent", "0");
}, function() {
    $(this)
    .animate({
        width: "5%"
    }, {
        queue: false,
        duration: 500
    }).css("text-indent", "100%");
});

FIDDLE: https://jsfiddle.net/lmgonzalves/znxygpdw/1/

like image 129
lmgonzalves Avatar answered Mar 25 '23 02:03

lmgonzalves


As mentioned above it would be better to use the hover function. However you problem lies with the mouseout function, when you hover over the link with the block the event is fired. To fix this, use the mouseleave function instead.

//Sidbar Animations
    $(".block").mouseover(function() {
      $(this)
        .animate({
          width: "90%"
        }, {
          queue: false,
          duration: 400
        }).css("text-indent", "0");
    });
    $(".block").mouseleave(function() {
      $(this)
        .animate({
          width: "5%"
        }, {
          queue: false,
          duration: 500
        }).css("text-indent", "100%");
    });

http://jsfiddle.net/znxygpdw/4/

like image 30
Muggles Avatar answered Mar 25 '23 01:03

Muggles