I’m using a Bootstrap navbar which hides when the user scrolls down and shows when the user scrolls up. Now I want to add a shadow if the navbar shows again after some scrolling.
There are two CSS classes for the showing/hiding of the navbar: .scrolled-down
and .scrolled-up
.
The problem with my code is that the .scrolled-up
class stays even if the user is back at the very top of the page. If I add a shadow to that class, it stays even if the user is back at the top.
Is there an option to add a third class like .on-top
? I could use box-shadow: none !important
for that and give the other two a shadow.
Here’s a working example of my code:
And here’s the code: https://codepen.io/cray_code/pen/qBMQdeo
CSS:
.scrolled-down {
transform: translateY(-100%);
transition: all 0.3s ease-in-out;
background: red !important;
}
.scrolled-up {
transform: translateY(0);
transition: all 0.3s ease-in-out;
background: green !important;
}
.autohide {
position: fixed !important;
top: 0;
right: 0;
left: 0;
width: 100%;
z-index: 1030;
}
Javascript:
document.addEventListener("DOMContentLoaded", function(){
el_autohide = document.querySelector('.autohide');
// add padding-top to bady (if necessary)
navbar_height = document.querySelector('.navbar').offsetHeight;
document.body.style.paddingTop = navbar_height + 'px';
if(el_autohide){
var last_scroll_top = 0;
window.addEventListener('scroll', function() {
let scroll_top = window.scrollY;
if(scroll_top < last_scroll_top) {
el_autohide.classList.remove('scrolled-down');
el_autohide.classList.add('scrolled-up');
}
else {
el_autohide.classList.remove('scrolled-up');
el_autohide.classList.add('scrolled-down');
}
last_scroll_top = scroll_top;
});
// window.addEventListener
}
// if
});
The code is from here: https://bootstrap-menu.com/detail-autohide.html
2
Answers
Add another
if
statement.All together. Demo
I hope that was your intention: