Toggle CSS property on scroll

I am currently trying to add a CSS property to a div when the user has scrolled a certain distance down the page.

<div id="navbar">...</div>
#navbar {
    position: fixed;
    width: 100%;
    height: 55px;
    padding: 1px;
    padding-left: 20px;
    background: #009688;
}

I want to add box-shadow: 0px 3px 2px #888888; property to the CSS for #navbar, when the user has scrolled 209px down the page. I have tried to put this together already with jQuery I found online, but as I have next to no experience with jQuery, I couldn't make it work.

$("#navbar").css("box-shadow", "0px 3px 2px #888888");

And:

$(document).scroll(function() {
    $('#navbar').toggle($(this).scrollTop()>209)
 });?

I hope I've made sense. Thank in advance for any help.

Answers 1

  • Create another class in your CSS and toggle it using javascript.

    CSS:

    .navbar-scrolled { box-shadow: 0px 3px 2px #888888; }

    Javascript:

    $(document).scroll(function() { $("#navbar").toggleClass("navbar-scrolled", $(document).scrollTop() >= 209); });

    Snippet below:

    $(document).scroll(function() {
      $("#navbar").toggleClass("navbar-scrolled", $(document).scrollTop() >= 209);
    });
    #navbar {
      position: fixed;
      width: 100%;
      height: 55px;
      padding: 1px;
      padding-left: 20px;
      background: #009688;
    }
    .navbar-scrolled {
      box-shadow: 0px 3px 2px #888888;
    }
    #page-filler {
      height: 1000px;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="navbar">navbar</div>
    <div id="page-filler"></div>


Related Articles