madhu kumar
madhu kumar

Reputation: 810

How to change background color when colors are scrolled down?

i have an image which has many colors. it is scrolled down in the page. if the image color stops at center of the page automatically the thumbnail image color should change. Thumbnail image color is written in css. How to do this task?

enter image description here

Upvotes: 1

Views: 185

Answers (3)

António Almeida
António Almeida

Reputation: 10087

Here is my solution: http://jsfiddle.net/2kc44/ or more complete.

I first declare an array of positions / colors.
You can simply use:

var colors = {
      0: "#FFFFFF",
    300: "#FF0000",
    600: "#00FF00",
    900: "#0000FF"
}

or with more paremeters:

var colors = {
      0: {c: "#FFFFFF", t: "White" },
    300: {c: "#FF0000", t: "Red"   },
    600: {c: "#00FF00", t: "Green" },
    900: {c: "#0000FF", t: "Blue"  }
}

This function:

$(window).scroll( changeBG );

function changeBG(e){
    var pos = $(window).scrollTop();
    for (var c in colors)
        if(pos >= c) $("body").css( { backgroundColor: colors[c] } );
}

It's clean, and its easy to add more colors, but it could be more optimized.

Upvotes: 2

Zword
Zword

Reputation: 6793

From what i have understood i created a fiddle:

http://jsfiddle.net/Zword/6Kkmf/

JQuery:

$(document).ready(function() {
    $("#colors").scroll(function(event) {
        $('.clor').each(function(){
        var s=$(this).attr('id');
        var r=s.substring(1,2);
        var calc=parseInt(r)-1;
        if($("#colors").scrollTop()>=($('.clor').height()*calc) && $("#colors").scrollTop()<($('.clor').height()*r))
        {
        var color=$('#'+s).css('backgroundColor');
        $("#preview").css({backgroundColor: color});
        }
        });
    });
});

Upvotes: 1

23tux
23tux

Reputation: 14736

Maybe a point to start from: http://jsfiddle.net/Z47mY/ Here you can define your colors based on the scroll position.

$(document).ready(function() {
    $(window).scroll(function(event) {
        var color="#ffffff";
        var position = $(window).scrollTop() / $(window).height();
        if(position > 0.3) {
            color="#ff0000";
        }
        if(position > 0.8) {
            color="#00ff00";
        }
        $("body").css({backgroundColor: color});
    });
});

Upvotes: 1

Related Questions