javascripthtmljquerycssjquery-scrollable

How can I Keep Scroll Position after refresh?


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 class="navbar navbar-expand-lg navbar-light p-4 fixed-top">
    <div class="container-fluid">

        <div class="collapse navbar-collapse" id="navbarSupportedContent">
            <ul class="navbar-nav ms-auto mb-2 mb-lg-0">
               <li class="nav-item px-1">
                   <a class="nav-link active lightgray" aria-current="page" href="#">Medicne</a>
               </li>
           </ul>
                    
       </div>
               
   </div>

style.css:

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

Solution

  • 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
    });