0

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;
}
1

1 Answer 1

1

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
});
2
  • How will this set a specific scroll position on page refresh?
    – isherwood
    Commented Oct 6, 2022 at 12:43
  • @isherwood static website's positions are handled by the browser, since there's no specification of SPA or lazy-loading I focused on the class problem instead of the behaviours already handled by the browser (notice that the content lays into a index.html file, hence static content)
    – savageGoat
    Commented Oct 6, 2022 at 14:46

Not the answer you're looking for? Browse other questions tagged or ask your own question.