Home > OS >  Scroll Event Not working on mobile with sticky
Scroll Event Not working on mobile with sticky

Time:08-29

Hi so im trying to change my navbar to sticky and apply it when the page is being scrolled. It works perfectly on desktop version with this code but it doesnt apply to the mobile version.

    window.addEventListener("scroll", function()
    {
    var nav=document.querySelector("nav")
    nav.classList.toggle("sticky", window.scrollY > 0)
    
    })       

CodePudding user response:

You shouldn't need to use an event listener. Have a look at position: sticky attribute here

CodePudding user response:

if parent element is nav it will work without js

// CSS
nav {
position: sticky
}

if it's header

// CSS
header {
position: sticky
}
  • Related