I just started learning jQuery and JS and I'm now having difficulties making some basic stuff.
I want to make the static navigation bar become fixed when the window reaches the end of the .hero-fullscreen
section and goes back to static if not.
$(window).on("scroll", function() { var navbar = $(".navbar"); if (navbar.offset().top > 150) { navbar.addClass(".navbar-fixed"); } else { navbar.removeClass(".navbar-fixed"); } });
.navbar { display: block; height: 50px; width: 100%; background-color: #000; } .navbar-static { position: static; } .navbar-fixed { position: fixed; } .hero-fullscreen { height: 100vh; width: 100%; background-color: red; } .random-section { height: 100vh; width: 100%; background-color: blue; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <nav class="navbar navbar-static"></nav> <section class="hero-fullscreen bg-image"></section> <section class="random-section"></section>
Now, my question is, instead of .top > 150
, what should be there so the navbar
becomes fixed when it reaches the bottom of the .hero-fullscreen
(the red one) section?
Thank you!
Basically you need to do two things:
window.addEventListener('load', getWindowHeight);
window.addEventListener('resize', getWindowHeight);
var endPos;
function getWindowHeight(){
var hei = window.innerHeight;
endPos = hei + 50;
}
document.addEventListener('scroll', trackScroll);
var navBar = document.getElementById('navbar');
function trackScroll() {
var scrollPos = document.body.scrollTop();
if (scrollPos > endPos) {
navBar.style.position = 'fixed';
} else {
navBar.style.position = 'static';
}
}
However, I've made it so that you'll have to give your navigation element an id
of navbar
, not a class
.
getWindowHeight
fulfills the first requirement. trackScroll
fulfills the second requirement and makes the necessary changes.
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.