Is there a better/more straightforward way of doing this?
function moveNav(){
var navOffset = $(".nav-marker").offset().top;
$(window).scroll(function() {
var scrollOffset = $(document).scrollTop();
if( scrollOffset >= navOffset ){
$(".nav-bar").addClass("scroll-fixed");
} else{
$(".nav-bar").removeClass("scroll-fixed");
}
});
}
moveNav();
// call again on resize to recompute navOffset
$(window).resize(function() {
moveNav();
});
I want to use the moveNav()
function again when the browser is resized but the way I'm currently doing it feels off. I feel like there's a way of moving the resize()
function inside the moveNav()
function but when I put it inside it, there's some lag happening when when I resize. You can see it happening here: https://jsfiddle.net/grj89t9b/2/
Is there a better way of doing this?
I would declare the variables first, and make a simpler function but then declare it both on $(window).resize()
and $(document).scroll()
.
var navOffset, scrollOffset;
function moveNav(){
navOffset = $(".nav-marker").offset().top;
scrollOffset = $(document).scrollTop();
if( scrollOffset >= navOffset ){
$(".nav-bar").addClass("scroll-fixed");
} else {
$(".nav-bar").removeClass("scroll-fixed");
}
}
moveNav();
$(document).scroll(function() { moveNav(); });
$(window).resize(function() { moveNav(); });
and it works on your JSFiddle .
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.