From Transparent To Solid Navbar

Viewed 364

I need help. Can someone tell me why this code isn't working? I linked HTML with CSS and JavaScript properly. I tried everything, and I checked the code carefully, but I didn't find any mistake. The code looks good but when I scroll, nothing happens.

I want to change the background color of the navbar from transparent to solid when scrolling.

$(document).ready(function()
{
    $(window).scroll(function()
    {
        if($(this).scrollTop() > 200)
        {
            $('.navbar').addClass('solid');
        }
        else
        {
            $('.navbar').removeClass('solid');
        }
    });
});
.navbar{ 
    width:100%;
    height:80px;
    display:flex;
    justify-content: space-between;
    background-color:transparent;
    font-family:'Poppins', sans-serif;
    position:fixed;
    transition:background-color 1s ease;
}

/*--Class to add on scroll--*/
.navbar.solid{
    background-color:#000;
    transition:background-color 1s ease;
}
<div class="navbar">
   <div class="logo">
      <a href="index.html"><h2>Plant<span>.</span></h2></a>
   </div>
   <div class="navbar-nav">
      <ul class="nav">
         <li class="nav-links active">Home</li>
         <li class="nav-links">About</li>
         <li class="nav-links">Contact</li>
         <li class="nav-links link4">Hire Us</li>
      </ul>
   </div>
</div>
1 Answers

Hi I am not sure if I've interpreted your question correctly as it's not very clear as to what exactly isn't working. But I think what you mean to imply is that the jquery code isn't working as expected. You might try executing this snippet:

$(window).scroll(function () {
        $('.navbar').toggleClass('solid', $(this).scrollTop() > 200);
});

Now you can define the 'solid' class however you want to and I hope it'll work!

Also, make sure that you've imported the jquery CDN properly.

Related