I'm trying to construct a nav bar that changes from height:'70px' to height:'50px' when the page is scrolled away from the top, and then changes back to height:'70px' whenever the page is scrolled back to the top.
To achieve this I've tried this code:
// JavaScript Document
$(document).ready(function() {
$(window).scroll(function () {
var scroll_top = $(this).scrollTop();
if (scroll_top > 0){
$('nav').animate({
height:'50px'
});
}else{
$('nav').animate({
height:'70px'
});
}
});
});
What happens with this code is that the page loads correctly, and the first time I scroll down the height animates fine. However, whenever I scroll back to top it either won't change back to height:'70px', or (and this last part happens a lot when I try to animate additional values such as width or opacity) the entire nav bar looks to be flickering as if it were caught in a loop.
I spoke to a programmer yesterday who said it sounded like the page was re-firing .animate any time the pixel value of the nav bar changed while animating, creating an infinite loop. He suggested I implement a return false; condition to remedy this, but I'm unsure how exactly to implement it. Any help?
Suggestions on how do achieve this same effect in a different, more effective manner would also be appreciated.
Make it a lot simpler:
Have some CSS:
nav {
height:50px;
transition:height 0.4s ease;
}
nav.scrolledFromTop {height:70px}
Now your jQuery:
$(window).scroll(function() {
$("nav")[this.scrollTop > 0 ? "addClass" : "removeClass"]("scrolledFromTop");
});
Done! That is the magic of CSS3 ;)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.