Random : colorChange()

By vaseline28 on Jan 03, 2009

This snippet changes the color of an element which is selected from a list when called (OR it can change the color of an object to a specified color).

To Setup:
Edit line:

b='505050 6633FF 000000 765981 149387 999999 666666 666999 FFF5CF' ;

to your list of colors to randomly pick from (6 digits necessary per color) e.g.

b='color1 color2 color3';

To Use:

For specified color change - Your HTML should look like this:

<div onclick='javascript:colorChange("colorHere", "ID of the Element to change the color of")'>

(NOTE: obviously replacing the "<div" tag with the tag for what you need, "colorHere" with your color, "ID of element etc." is self explanatory :) and onclick for whatever event to trigger.)

For random color change - Your HTML should look like this:

<div onclick='javascript:colorChange("rand", "ID of the Element to change the color of")'>

(NOTE: obviously replacing the "<div" tag with the tag for what you need, "ID of element etc." is self explanatory :) and onclick for whatever event to trigger.)

Colors currently MUST have 6 characters - but that's a standard number for a Hex Color Code anyway.

Tested in Firefox and IE.

function colorChange (type,docEl) {
  if (type!='rand') 
  {
      document.getElementById(docEl).style.backgroundColor=type ;
  }
  else 
  {
      b='505050 6633FF 000000 765981 149387 999999 666666 666999 FFF5CF' ;
      c=Math.random() ;  g=0 ;  f=0 ;
      randomcolor = new Array() ;

      while (g<b.length/7) 
      {
        randomcolor[g] = b.slice(f,b.indexOf(" ")+f) ;
        g=g+1 ; f=f+7 ;
      }

      l=1/g ; h=0 ;
      while (l<c) 
      {
        l=l+l ; h=h+1 ;
      }
      colorChange(randomcolor[h],docEl) ;
   }
}

Comments

Sign in to comment.
Are you sure you want to unfollow this person?
Are you sure you want to delete this?
Click "Unsubscribe" to stop receiving notices pertaining to this post.
Click "Subscribe" to resume notices pertaining to this post.