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.