Reputation: 731
The following jQuery code:
HTML:
<header class="header">
<div class="navbar">
Hello
</div>
</header>
CSS:
.header {
background-color: black;
height: 1000px;
width: 300px;
color: white;
text-align: center;
padding: 30px;
}
.fixed .navbar{
border: 10px solid red;
position: fixed;
background-color: white;
}
.navbar {
background-color: blue;
height: 50px;
width: 300px;
color: white;
}
JS:
$(window).scroll( function(){
if($(window).scrollTop() > 200) $("header").addClass("fixed");
else $("header").removeClass("fixed");
});
does work.
But when I add it to my homepage, I have to refresh the page for the "fixed" class to be added. But I want the class to be added live, while scrolling down, without the page having to be refreshed. This works in jsfiddle, why doesnt it work on my page?
My page: Click here
Upvotes: 3
Views: 1174
Reputation: 2395
As Karl-André said, your $
object is being overwritten. To make your code work you can do either of the following:
Use the jQuery
object:
jQuery(window).scroll( function(){
if(jQuery(window).scrollTop() > 200) jQuery("header").addClass("fixed");
else jQuery("header").removeClass("fixed");
});
Or wrap everything in a self-executing function, passing the jQuery
object as an argument:
(function($)
{
$(window).scroll( function(){
if($(window).scrollTop() > 200) $("header").addClass("fixed");
else $("header").removeClass("fixed");
});
}(jQuery))
Upvotes: 4
Reputation: 1258
Try using
$(function() {
$(window).on('scroll', function(){
if($(this).scrollTop() > 200) $("header").addClass("fixed");
else $("header").removeClass("fixed");
});
});
Upvotes: 1