jquery random colours

Go To StackoverFlow.com

0

Hi I am trying to get this script to show random colours one after the other when the li scrolls up but so far I have it doing this but it is not smooth it changes when it restarts so you dont get smooth effect and it changes colour twice any help will be great thanks.

 $("#carousel ul").animate({marginTop:-100},2000,function(){

    function pad(s,i,c,r){
    i=i+1-s.length;
    if(i<1)return s;
    c=new Array(i).join(c||" ");
    return r?s+c:c+s;
    };

    hue  = "#"+pad((Math.random()*0x1000000<<0).toString(16),6,"0");
    hue2 = "#"+pad((Math.random()*0x1000000<<0).toString(16),6,"0");
    hue3 = "#"+pad((Math.random()*0x1000000<<0).toString(16),6,"0");

    $(this).find("li:last").after($(this).find("li:first"));
    $('#div1').css({backgroundColor: hue});
    $('#div2').css({backgroundColor: hue2}); 
    $('#div3').css({backgroundColor: hue3});

    $(this).css({marginTop:0});
    })  
    },1000);  
});

my example can be found here http://swipedstudio.com/jtoy/ Thanks in advance!

2012-04-03 21:30
by Sam Miller
Is the problem that after the initial load you don't want to "top" color to change color each time, only the bottom as it rotates up - ramblinjan 2012-04-03 23:06
No , There is 3 divs so far but what I want is that they change colour when they are hidden and not as it is now when they are at top as the flash another colour before they scroll - Sam Miller 2012-04-05 11:57


0

Working code:

var t = setInterval(function(){ 

 $("#carousel ul").animate({marginTop:-100},2000,function(){

    function pad(s,i,c,r){
    i=i+1-s.length;
    if(i<1)return s;
    c=new Array(i).join(c||" ");
    return r?s+c:c+s;
    };

    hue  = "#"+pad((Math.random()*0x1000000<<0).toString(16),6,"0");

    $(this).find("li:last div").css({backgroundColor: hue});
    $(this).find("li:last").after($(this).find("li:first"));

    $(this).css({marginTop:0});
    })  
    },1000); 

The issues:

  • You were changing the color of every div on every interval when really you only wanted to change the last one in the list
  • When you change the color of the last div, you need to select it using $(li:last div) because the three divs cycle through the list. When you select div1, div2, or div3 specifically, it could be at any place in the list
  • The color change (at least with the $(li:last div) selector) needed to take place prior to the after() statement. Your original code changes the order of the divs and then changes the color
2012-04-05 19:32
by ramblinjan
Thanks! works perfect and the way you explained it was spot on - Sam Miller 2012-04-07 17:42
No problem! Could you click the check on the left side of the answer to accept it - ramblinjan 2012-04-08 00:08
Just done it .. I did try the up arrow but said vote up requires 15 reputation. Thank - Sam Miller 2012-04-09 09:35