Reputation: 741
I'm making a site with a header fixed on the top (it will contain the nav). When this header slides over a specific div, I want it to animate to the color of that section.
I have decided to do this by using jQuery to add the animation class 'toRed' to my header, when the page has scrolled down a specific percentage.
var scrollPercentage = 100 * ($(this).scrollTop() / $('body').height());
$(window).scroll(function () {
if ( 50 <= scrollPercentage >= 75){
$('header').addClass('toRed');
}
});
JSFiddle : http://jsfiddle.net/5q8nH/16/
So to explain the fiddle, when the page is scrolled down to the red section, ie between 50% and 75% of the page, I want the header to animate via 'toRed' and turn red to the color of the div.
Upvotes: 0
Views: 2484
Reputation: 707716
You have to recalculate your scrollPercentage
inside the event handler so it is recalculated on each event and you have to fix your comparison too.
$(window).scroll(function () {
var scrollPercentage = 100 * ($(this).scrollTop() / $('body').height());
if (scrollPercentage >= 50 && scrollPercentage <= 75){
$('header').addClass('toRed');
}
});
And, I suspect, you probably need to remove the class when the scrollPercentage
is not in the right range so this isn't a one-way transition that can never be undone:
$(window).scroll(function () {
var scrollPercentage = 100 * ($(this).scrollTop() / $('body').height());
if (scrollPercentage >= 50 && scrollPercentage <= 75){
$('header').addClass('toRed');
} else {
$('header').removeClass('toRed');
}
});
Looking at your jsFiddle, you can simplify your multiple comparisons by reording them like this:
$(window).scroll(function () {
var scrollPercentage = 100 * ($(this).scrollTop() / $('body').height());
var newClass;
if (scrollPercentage >= 75){
newClass = 'toGreen';
} else if (scrollPercentage >= 50) {
newClass = 'toRed';
} else if (scrollPercentage >= 25) {
newClass = 'toYellow';
} else {
newClass = 'toBlue';
}
$('header').removeClass('toGreen toBlue toRed toYellow').addClass(newClass);
});
You can see the appropriate class being applied as you scroll here in this modified jsFiddle: http://jsfiddle.net/jfriend00/6vznD/. I'm not sure what you were trying to do with the animations - that part does not seem functional, but the class assignment is now working properly for each separate quarter of the scroll range. You may want to change the colors for each particular range as they don't seem to match what you have in the background.
Upvotes: 3