skip to Main Content

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


  1. You can reduce it to two ternaries, but it’s not necessarily better or more readable.

    const predicate = (scrollPosition >= 600);
    scrollDown.classList.add(predicate ? 'is-hidden' : 'is-visible');
    scrollDown.classList.remove(predicate ? 'is-visible' : 'is-hidden');
    

    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 with display: none; that you can add or remove depending on what you want to accomplish.

    Login or Signup to reply.
  2. How about this?

    const navbar = document.querySelector('.navbar');
    
    window.addEventListener('scroll', function() {
      const scrollPosition = window.scrollY;
      const shouldHideNavbar = scrollPosition >= 600;
    
      navbar.classList.toggle('is-hidden', shouldHideNavbar);
      navbar.classList.toggle('is-visible', !shouldHideNavbar);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search