Reputation: 3469
Trying to apply css to my navigation when user is at the top of the page. This is my code but it's not working
html
<script>
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 200) {
$("#s-nav").addClass('nav-anim');
} else $("#s-nav").removeClass('nav-anim');
});
</script>
css
#s-nav {
position: fixed;
display: block;
z-index: 999;
width: 100%;
padding: 0; margin: 0;
top: 0; left: 0;
background-color: red;
}
.nav-anim {
margin: 40px 0;
}
Upvotes: 1
Views: 53
Reputation: 90013
Your script is working, but when you apply the class .nav-anim
to #s-nav
it will not apply margin:40px 0;
because the #s-nav
selector is an id and is more specific than .nav-anim
, which is a class.
If you want it to apply, you need to make the selector stronger (id + class): #s-nav.nav-anim {}
Working example:
$(window).scroll(function() {
var scroll = $(window).scrollTop();
if (scroll >= 100) {
$("#s-nav").addClass('nav-anim');
} else
$("#s-nav").removeClass('nav-anim');
});
#s-nav {
position: fixed;
display: block;
z-index: 999;
width: 100%;
padding: 0; margin: 0;
top: 0; left: 0;
background-color: red;
transition: margin .3s cubic-bezier(.4,0,.2,1);
}
#s-nav.nav-anim { /* < --- here's the juice */
margin: 40px 0;
}
body {
min-height: 200vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="s-nav">S nav</div>
Upvotes: 2