I have an element that I want to stick on top after it reaches the top of the screen.
<div id="HeaderWrapper">
...
<div id="Navigation">
Navigation
</div>
...
</div>
I add an event listener on scroll
, which calls a function to check the placement of an element using the method getBoundingClientRect()
. If top
either the y
element is less than 0 relative to the viewport, I would like to fix / insert the title. Again, if it is greater than 0, I would like to remove the commit position. In both cases, I add and remove the name of a class fixed_navbar
that has a fixed position property.
document.addEventListener("scroll", function() {
const el = document.getElementById("Navigation");
let rect = el.getBoundingClientRect();
if (rect.top <= 0) {
el.classList.add("fixed_navbar");
} else {
el.classList.remove("fixed_navbar");
}
});
You can also check out the codepen demo .
, . , 0, . , , 0, - . , , , , ?