I’ve recently been using this set up on a website…
CSS
body {
height:2000px;
}
#top-box {
position:fixed;
width:200px;
height:200px;
margin-left:100px;
margin-top:50px;
background-color:blue;
z-index:2;
}
#bottom-box {
position:fixed;
width:200px;
height:200px;
margin-left:110px;
margin-top:60px;
background-color:red;
z-index:1;
}
JavaScript
$(document).ready(function() {
var away = false;
$(document).scroll(function() {
if ($(document).scrollTop() > 250) {
if (!away) {
away = true;
$('#bottom-box').stop().animate({
'margin-top': '200px'
}, 1500);
}
} else {
away = false;
$('#bottom-box').stop().animate({
'margin-top': '60px'
}, 0);
}
});
});
HTML
<div id="top-box"></div>
<div id="bottom-box"></div>
This makes it so that once the user scrolls 250 pixels down the page, the red box animates and slides out from underneath the blue box. This first animation is timed so that the transition is obvious (the red box visibly slides out).
It is then set so that if the user scrolls back above 250 pixels, the red box moves back under the blue box. This is done without a timer so the transition is instant (the red box snaps back to it’s original place).
This works fine and does everything I need it to do. But I am curious as to whether there is a better way to achieve this second animation, without using an animate at all and just having the red box “reset” to “margin-top:60px” without the need to have timing or .animate?
Essentially, I am asking could the…
$('#bottom-box').stop().animate({
'margin-top': '60px'
}, 0);
section of the JavaScript be written differently and more efficiently to achieve the same result but without using an animate? Like a sort of “set ‘bottom-box’ to ‘margin-top’: ’60px'”?
I think using jquery .css is neater
http://jsfiddle.net/mnRNE/1/
Does the trick