Mostafa Talebi
Mostafa Talebi

Reputation: 9173

How to animate a position of a fixed element with jQuery

I have a div whose position properties is:

.some
{
    position: fixed;
    top: 0px;
}

I then want to animate its bottom (not with top, with bottom property)

$(document).ready(function(){

                  $("a").on("click", function(e){
    e.preventDefault();
                      $("div").animate({ top: "none", bottom : 25});    
        });
});

But it does not work. The problem is that top property is in the priority. If I set the top to 0 then it sticks to the top, it does not care any to bottom value. However I remove the top property and animate bottom, it starts the animation right from the very bottom. I want the animation to start from the position which is designated by top value and end in where it is specified by bottom value. What should I do?

Here is the JSFiddle:

http://jsfiddle.net/mostafatalebi2/ex1b69g9/

Upvotes: 2

Views: 13248

Answers (2)

Marco Bonelli
Marco Bonelli

Reputation: 69276

You should animate from top: 0 to top: 100% using a negative margin-top value to maintain the div at a certain distance from the bottom of the page. Doing so, your div will move from the very top to the bottom of the page, like you want.

To move your div exactly 25 pixels distant from the bottom you can set margin-top to the negative value of your div's height minus 25px.

Here's an example:

$(document).ready(function() {
    $("a").on("click", function(e) {
        e.preventDefault();
        var $div = $('div.some');
        $div.animate({
            top: '100%',
            marginTop: - $div.height() - 25
        });
    });
});
.some {
  position: fixed;
  top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div class='some'>I am a DIV!</div>
<br/>
<br/>
<a href='#'>Click Here!</a>

Upvotes: 5

EddNewGate
EddNewGate

Reputation: 537

$(document).ready(function(){

                  $("a").on("click", function(e){
    e.preventDefault();
                      $("div").animate({ top:'500px'});    
        });
});

Fiddle: http://jsfiddle.net/gcsx1exj/1/

Upvotes: -1

Related Questions