Hi I’m in the process of learning JS and wrote this function which simply hides an element such as navbar on scroll, however the only way I could think of writing this without looking for an answer online was like below:
let scrollPosition = window.scrollY;
const scrollDown = document.querySelector('.navbar');
window.addEventListener('scroll', function() {
scrollPosition = window.scrollY;
if (scrollPosition >= 600) {
scrollDown.classList.add('is-hidden');
scrollDown.classList.remove('is-visible');
} else {
scrollDown.classList.remove('is-hidden');
scrollDown.classList.add('is-visible');
}
});
I get a strong feeling that my code is not dry and I’m repeating myself and seassoned Js developer could help me if that is the case.
If the code looks fine to you also please let me know 😀
Cheers
2
Answers
You can reduce it to two ternaries, but it’s not necessarily better or more readable.
Why do you have two different CSS rules for hidden and visible? What exactly are you trying to do? It is probably enough to just have a
.hidden
withdisplay: none;
that you can add or remove depending on what you want to accomplish.How about this?