Reputation: 413
I have this code that changes the background-color on scroll, but it only changes from the "beginning-color" to the "ending-color", is it possible to include another colors between them?
$(document).ready(function(){
var scroll_pos = 0;
var animation_begin_pos = 0;
var animation_end_pos = $(document).height();
var beginning_color = new $.Color( 'rgb(140,212,208)' );
var ending_color = new $.Color( 'rgb(145,216,247)' ); ;//what color we want to use in the end
$(document).scroll(function() {
scroll_pos = $(this).scrollTop();
if(scroll_pos >= animation_begin_pos && scroll_pos <= animation_end_pos ) {
// console.log( 'scrolling and animating' );
//we want to calculate the relevant transitional rgb value
var percentScrolled = scroll_pos / ( animation_end_pos - animation_begin_pos );
var newRed = beginning_color.red() + ( ( ending_color.red() - beginning_color.red() ) * percentScrolled );
var newGreen = beginning_color.green() + ( ( ending_color.green() - beginning_color.green() ) * percentScrolled );
var newBlue = beginning_color.blue() + ( ( ending_color.blue() - beginning_color.blue() ) * percentScrolled );
var newColor = new $.Color( newRed, newGreen, newBlue );
//console.log( newColor.red(), newColor.green(), newColor.blue() );
$('body').animate({ backgroundColor: newColor }, 0);
} else if ( scroll_pos > animation_end_pos ) {
$('body').animate({ backgroundColor: ending_color }, 0);
} else if ( scroll_pos < animation_begin_pos ) {
$('body').animate({ backgroundColor: beginning_color }, 0);
} else { }
});
});
Upvotes: 1
Views: 583
Reputation: 41832
Updated : with five background colors.
Just do the following:
$(document).ready(function(){
var colorCodes = ['red','blue','green','yellow','orange'];
$(window).on('scroll',function(){
var value = $('body').scrollTop()%5;
$('body').animate({
backgroundColor: colorCodes[value]
}, 100 );
});
});
Change the color codes based on the value of scrollTop().
Take a array of you own color codes and call them based on the scrollTop() value.
Upvotes: 2
Reputation: 361
create a random color code using the following script..
var colorcode= 'rgb('
+ (Math.floor(Math.random() * 256)) + ','
+ (Math.floor(Math.random() * 256)) + ','
+ (Math.floor(Math.random() * 256)) + ')';
Upvotes: 1