javascript - I can't get my navigation to change on scroll -
i know repeat question, trying navigation bar change styling using javascript/jquery/css making jquery add , remove classes depending on position of scrollbar, yet no prevail. huge noob jquery. tell me if these wrong code. have searched hours , can't find , error. here working example: http://codepen.io/anon/pen/qbwojv , here code:
// on scroll, $(window).on('scroll',function(){ // round here reduce little workload stop = math.round($(window).scrolltop()); if (stop > 50) { $('.nav').addclass('passed-main'); } else { $('.nav').removeclass('passed-main'); }
.nav { background-color: #000000; opacity: 0.3; width: 100%; height: 40px; position: fixed; top: 0; z-index: 2000; transition: 0.3s; } .nav.past-main { background-color: #ffffff; opacity: 1; }
<div class="nav"> </div>
perhaps example want achieve, , when try code above, it's not working.
here's problem code in snippet:
you forgot close function
// on scroll, $(window).on('scroll',function(){ // round here reduce little workload stop = math.round($(window).scrolltop()); if (stop > 50) { $('.nav').addclass('passed-main'); } else { $('.nav').removeclass('passed-main'); } }); // forgot close function here
you add/remove class
passed-main
while incss
you're using class selector.nav.past-main
your window doesn't have scrollbar, need add
css
test if worksbody { height: 1500px; }
you forgot include
jquery
in snippet.
here's working updated snippet
// on scroll, $(window).on('scroll', function () { // round here reduce little workload stop = math.round($(window).scrolltop()); if (stop > 50) { $('.nav').addclass('past-main'); } else { $('.nav').removeclass('past-main'); } });
.nav { background-color: #000000; opacity: 0.3; width: 100%; height: 40px; position: fixed; top: 0; z-index: 2000; transition: 0.3s; } .nav.past-main { background-color: #ffffff; opacity: 1; } body { height: 1500px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <div class="nav"></div>