I need help modifying sticky navbar

I have been using a sticky navbar for some time, but I would like to modify it, so that when the navbar becomes fixed upon scrolling, a new list item will become visible.

In my HTML I have created two classes for my list items.

        <ul class="navbar-nav me-auto mb-2 mb-lg-0">
          <li class="nav-item">
            <a class="nav-link" href="#">Link 1</a>
          </li>
          <li id="nav-item-on-scroll">
            <a class="nav-link" href="#">Link 2</a>
          </li>
        </ul>

In my CSS the link with the ID of “nav-item-on-scroll” is set to display: NONE.
So in my JS file, I tried to write a new function that changes the display of the ID to BLOCK when the navbar sticks.
But it does not work.

const nav = document.querySelector('#navbar');
const linkScroll = document.querySelector('#nav-item-on-scroll');
let navTop = nav.offsetTop;

function fixedNav() {
  if (window.scrollY >= navTop) {
    nav.classList.add('fixed');
  } else {
    nav.classList.remove('fixed');
  }
}
function showLink() {
  if(window.scrollY >= navTop) {
    linkScroll.style.display = "block";
  } else {
    linkScroll.style.display = "none";
  }
}

window.addEventListener('scroll', fixedNav, showLink);

You can’t pass two handler functions to addEventListener the third argument is the options object. You can attach more than one handler function to the same element but then it has to use separate addEventListener calls. You usually wouldn’t do that for the same event type either more likely you would consolidate the code inside one handler function.

Can’t you just put the style change code inside the fixedNav function?

function fixedNav() {
  if (window.scrollY >= navTop) {
    nav.classList.add('fixed');
	linkScroll.style.display = "block";
  } else {
    nav.classList.remove('fixed');
	linkScroll.style.display = "none";
  }
}

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.