Home > Software design >  How can I Keep Scroll Position after refresh?
How can I Keep Scroll Position after refresh?

Time:10-07

Can anyone tell me where I'm doing wrong? When I scroll It works well, nav background color being changed. But problem is, when I refresh the page then the background color not changing, It goes in the initial condition. At this position, if I again scroll it works well like before. What is the problem?

index.js:

$(function () {
    $(window).scroll(function(){
        var scroll = $(window).scrollTop();
        if(scroll>200){
            $("nav").addClass("nav_bg");
        }else{
            $("nav").removeClass("nav_bg");
        }

        
    })
});

index.html:

<nav >
    <div >

        <div  id="navbarSupportedContent">
            <ul >
               <li >
                   <a  aria-current="page" href="#">Medicne</a>
               </li>
           </ul>
                    
       </div>
               
   </div>

style.css:

.nav_bg{
    transition: 0.9s;
    background-color: #008f84 !important;
}

CodePudding user response:

But problem is, when I refresh the page then the background color not changing

The function is being called only on scroll by this portion of the code $(window).scroll. You need to run the function on load as well

const ChangeNavOnScroll = () => {
    var scroll = $(window).scrollTop();
    if(scroll>200){
        $("nav").addClass("nav_bg");
    }else{
        $("nav").removeClass("nav_bg");
    }
};

$(function () {
    $(window).scroll(ChangeNavOnScroll) // run on scroll
    ChangeNavOnScroll(); // run when index.js is loaded
});
  • Related