Reputation: 29
I am creating a navigation menu for a website. When the user scrolls past the point 497px it needs to change colour. I have wrote this script:
$(document).ready(function(){
function checkOffset() {
var offset = $(document).scrollTop();
console.log(offset);
if(offset > 497){
$("#fixedBar").animate({backgroundColor: '#1B1B1B'}, 1000);
$("#fixedBar nav a").animate({color: '#FFF'}, 1000);
}else{
$("#fixedBar").animate({backgroundColor: '#FFF'}, 1000);
$("nav a").animate({color: '#1B1B1B'}, 1000);
}
}
$(window).scroll(function() {
checkOffset();
});
});
If I refresh the page and it is past that point then it indeed changes, however if I simply scroll past that point then it doesn't change. How can I fix this?
Upvotes: 2
Views: 88
Reputation: 4288
To use .animate()
with colors, you will need jQueryUI. So, add the framework to your head:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js""></script>
Then, try it again (I modified a little your current code):
$(function(){
$(window).on('scroll', function() {
checkOffset();
});
});
function checkOffset() {
var $target = $('#fixedBar');
var offset = $(window).scrollTop();
console.log(offset);
if(offset >= 10){
$target.stop(true, false).animate({ 'background-color': 'green'}, 1000);
//$("#fixedBar nav a").animate({color: '#FFF'}, 1000);
}
else if( offset < 10 ){
$target.stop(true, false).animate({ 'background-color': 'blue' }, 1000);
//$("nav a").animate({color: '#1B1B1B'}, 1000);
}
}
Upvotes: 1
Reputation: 981
Your script probably works.
But since you are animating on every scroll. there is a chance of having consecutive animation cycles.
Possible solutions would be (Any one of these points),
css
method rather than animate
stop()
before animating should help.animate
methodTo know more about stop() in jQuery.
Upvotes: 1
Reputation: 773
You should call checkOffset(); one more time:
$(document).ready(function(){
function checkOffset() {
var offset = $(document).scrollTop();
console.log(offset);
if(offset > 497){
$("#fixedBar").animate({backgroundColor: '#1B1B1B'}, 1000);
$("#fixedBar nav a").animate({color: '#FFF'}, 1000);
} else {
$("#fixedBar").animate({backgroundColor: '#FFF'}, 1000);
$("nav a").animate({color: '#1B1B1B'}, 1000);
}
}
$(window).scroll(function() {
checkOffset();
});
checkOffset(); // <-- HERE
});
Upvotes: 0