Search code examples
javascripthtmlcsstabs

nav sticky conflicting with tabs


Am building a website with a fairly complex nav that is sticky.It uses the following javascript to make it sticky:

/my sticky nav to make nav stick to top on scroll/

 document.addEventListener("scroll", function() {
        const distanceFromTop = Math.abs(
          document.body.getBoundingClientRect().top
        );
        const navbarHeight = 150;
        const navbar = document.querySelector(".navbar");
        if (distanceFromTop >= navbarHeight) navbar.classList.add("fixed-top");
        else navbar.classList.remove("fixed-top");
      });

I am also creating a dynamic tab component on one page of the website using the following found here:https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_tabs_open

It seems that the dynamic links stop working on scroll and will only work if the sticky javascript is removed? There is somthing in the javascript for the sticky nav that is preventing the dynamic tabs from working. I am a coding noob, so any help or suggetions on how to perhaps modify the javascrips to stop affecting the dynamic tabs would be so greatful.


Solution

  • Separate the scroll event listeners:

    // Sticky navigation
    document.addEventListener("scroll", function() {
        const distanceFromTop = Math.abs(document.body.getBoundingClientRect().top);
        const navbarHeight = 150;
        const navbar = document.querySelector(".navbar");
        if (distanceFromTop >= navbarHeight) 
            navbar.classList.add("fixed-top");
        else 
            navbar.classList.remove("fixed-top");
    });
    
    // Dynamic tabs - Assuming this is how the tab clicks are handled
    document.querySelectorAll('.tablinks').forEach(tablink => {
        tablink.addEventListener('click', function() {
            // Your tab switching logic here
        });
    });