I need help making a navigation menu that shows up when users scroll upward and also appears when they get to the bottom of the page. I want something similar to what you see on popular sports brand websites. My current JavaScript code is not working properly and I can’t figure out what’s wrong with it.
const header = document.getElementById('mainHeader');
let headerPosition = header.offsetTop;
function toggleHeader() {
if (window.pageYOffset >= headerPosition) {
document.body.style.marginTop = header.offsetHeight + 'px';
document.body.classList.add('sticky-header');
} else {
document.body.style.marginTop = 0;
document.body.classList.remove('sticky-header');
}
}
window.addEventListener('scroll', toggleHeader);
// display header when user reaches bottom
window.addEventListener('scroll', function() {
if ((window.innerHeight + window.pageYOffset) >= document.documentElement.scrollHeight) {
header.classList.add('visible-header');
} else {
header.classList.remove('visible-header');
}
});
.dropdown-menu {
display: none;
}
<header>
<ul class="menu-items" id="mainHeader">
<li>
<a href="#">Home</a>
<ul class="dropdown-menu">
<li>
<a href="#">Link</a>
</li>
</ul>
</li>
</ul>
</header>
Your code structure needs refinement for proper scroll direction tracking. The primary problem is that you have two separate scroll event listeners when you should consolidate them into one optimized function. You need to store the previous scroll position and calculate the difference to determine scroll direction. Also, your HTML structure has the header wrapping the ul element, but your JavaScript targets the ul directly with getElementById. This mismatch could cause issues. Consider throttling your scroll events using requestAnimationFrame to improve performance, especially on mobile devices. The CSS classes you’re adding need corresponding styles to actually show or hide the navigation. Make sure your sticky-header and visible-header classes have the appropriate positioning and visibility properties defined.
The main issue here is the lack of scroll direction detection. To effectively show the navigation bar on scrolling up, you should track the previous scroll position. By comparing it with the current scroll position, you can determine if the user is scrolling upward. Additionally, consider merging your scroll event listeners into a single function to improve performance. I noticed your JavaScript targets the ul directly, but your HTML wraps it in a header, so make sure your styles for ‘sticky-header’ and ‘visible-header’ are correctly implemented to achieve the desired effect.
hey there! i think ur missing the scroll direction detection. you need to track the previous scroll position and compare it with current one to know when user scrolls up. try adding let lastScrollTop = 0;
and check if scrollTop < lastScrollTop
for upward scroll detection in ur event listener.