Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Animation

It's simple slide up animation. The problem is when I change "top" parameter of myDiv class, animation is working incorrectly, instead of sliding up, it slides down from top. It only works incorrectly when I click button for the first time. When I change myDiv's top parameter to a bigger number there is no more problem. Can you please help me to find what is wrong with the code.

   <style>
    .box {
        position:relative;
        width: 200px;
        height: 500px;
    }
    .myDiv {
        position: absolute;
        width:100%;
        overflow: hidden;
        bottom:0px;
        top:10px;
        left:500;
    }
</style>
<script>
    var swt = 0;
    $(document).ready(function () {
        $(".b1").click(function () {

            var div = $(".myDiv");
            if (swt == 0) {
                div.animate({
                    top: '300px',
                    opacity: '1'
                }, "slow");
                //  div.animate({height:'300px', opacity:'1'},"slow");
                swt++;
            } else {
                div.animate({
                    top: '500px',
                    opacity: '1'
                }, "slow");
                //  div.animate({height:'0px', opacity:'1'},"slow");
                swt--;
            }
        });
    });
</script>
</head>
<body>
    <button class="b1">Start Animation</button>
    <p>posds</p>
    <div class="box">
        <div class="myDiv" style="background:#7549B1; width:200px;"></div>
    </div>
</body>

</html>
like image 235
John Snau Avatar asked May 05 '26 15:05

John Snau


2 Answers

I'm not really sure whay effect do you want, but maybe it's changing the bottom value instead of top:

if(swt==0){
    div.animate({bottom:'500px', opacity:'1'}, "slow");
    swt++;  
} else {
    div.animate({bottom:'300px', opacity:'1'}, "slow");
    swt--;
}

http://jsbin.com/ixigaf/1/edit

like image 129
bfavaretto Avatar answered May 08 '26 05:05

bfavaretto


Do not use bottom and top on a same element, it will create a conflict. Define height and animte top with negative value:

Here is jsFiddle.

if(swt==0){
       div.animate({top:'-300px', opacity:'1'}, "slow");
        swt++;  
}else{
      div.animate({top:'-500px', opacity:'1'}, "slow");
        swt--;
}
like image 31
Barlas Apaydin Avatar answered May 08 '26 03:05

Barlas Apaydin