To achieve a fixed position for the navbar until a certain point is reached during scrolling, then switch it to relative within the scrolling container, follow these steps:
Here's an example demonstrating this concept: https://jsfiddle.net/n97tu7nt/
In the HTML section:
<div id="main-container">
<div class="nav" id="nav" style="position:fixed; height: 100px; background-color: blue; color: white; width:100%;">
This is the Nav Bar <span id="pos"></span>
</div>
<div style="position:relative; top:130px;" id="container">
<p>
This is some text
</p>
...
For the Javascript part:
var c = document.getElementById('nav');
var t = document.getElementById('container');
var p = document.getElementById('pos');
p.innerHTML = window.scrollY;
var last_known_scroll_position = 0;
var ticking = false;
function adjustPosition(scroll_pos) {
p.innerHTML = scroll_pos;
if (scroll_pos > 100) {
c.style.position = 'relative';
t.style.top = 0;
}
}
// Adapted from https://developer.mozilla.org/en-US/docs/Web/Events/scroll
window.addEventListener('scroll', function(e) {
last_known_scroll_position = window.scrollY;
if (!ticking) {
window.requestAnimationFrame(function() {
adjustPosition(last_known_scroll_position);
ticking = false;
});
ticking = true;
}
});
This might seem like a hacky solution, but it effectively illustrates the underlying principle.