View Full Version : Random colour
thehealey
05-19-2007, 05:27 PM
I'm making a new website & I want to know if it’s possible for the background colour to be randomly selected from a list of hex codes? So every time you go to the page there’s a different background colour.
Thanks in advance.:)
<script type="text/javascript" src="http://www.twey.co.uk/pythonic.js"></script>
<script type="text/javascript">
Twey.Pythonic.LOAD("Array.randomChoice");
document.body.style.backgroundColor = "#" + [
"fff",
"000",
"00f",
"0ff",
"0f0",
"fff000"
].randomChoice();
</script>Be careful that there's no text directly on top of this colour, though, or it might be unreadable sometimes. Also, don't forget users without scripting support -- always provide a default background colour or, if possible, generate the random colour server-side.
jscheuer1
05-20-2007, 04:44 AM
This cannot be done with just HTML.
Bob90
05-20-2007, 08:54 AM
I don't think loading an external script is really worth the hassle for such a simple script.
Having the script in the page eliminates the hotlinking to your own site and allows the coder to find out whats actually happening easier. (Twey, your external code is too sophisticated for begginers to understand.)
<script type="text/javascript">
colors = new Array();
colors[0] = "#FF0000";
colors[1] = "#FFCC00";
colors[2] = "#00FF00";
colors[3] = "#0000FF";
colors[4] = "#00FFCC";
colors[5] = "#CCFF00";
//etc
randomNumber = Math.floor(Math.random()*colors.length);
document.body.style.backgroundColor = colors[randomNumber];
</script>
:)
I don't think loading an external script is really worth the hassle for such a simple script.Mm, probably true.
Having the script in the page eliminates the hotlinking to your own site and allows the coder to find out whats actually happening easier.They could always download it, or even copy-and-paste it into the script wholesale. It's only there for convenience.
<script>The type attribute is required.
colors = new Array();
colors[0] = "#FF0000";
colors[1] = "#FFCC00";
colors[2] = "#00FF00";
colors[3] = "#0000FF";
colors[4] = "#00FFCC";
colors[5] = "#CCFF00";That's a lot of assignments. I think it would be more efficient and certainly easier to use an array literal. There's also no need for all those globals; to avoid cluttering the global namespace, perhaps wrap it in a new scope:
<script type="text/javascript">
(function() {
var colours = [
"#FF0000",
"#FFCC00",
"#00FF00",
"#0000FF",
"#00FFCC",
"#CCFF00"
];
document.body.style.backgroundColor = colours[Math.floor(Math.random() * colours.length)];
})();
</script>
(function() {
var colours = [
"#FF0000",
"#FFCC00",
"#00FF00",
"#0000FF",
"#00FFCC",
"#CCFF00"
];
document.body.style.backgroundColor = colours[Math.floor(Math.random() * colours.length)];
})();
Just wondering, why are you using this anonymous function syntax?
So colours doesn't end up global. I'm not entirely sure if the cost of creating and running a function is worth it, but John reckon(s|ed) that it is.
Bob90
05-20-2007, 11:04 AM
Very interesting points.
I didn't think about global declaration, I was just supplying the level of solution I thought met the request (i.e new coder requesting something very easy; they obviously need an introduction to most things.)
:)
So colours doesn't end up global. I'm not entirely sure if the cost of creating and running a function is worth it, but John reckon(s|ed) that it is.
I see.
Yet there's one "bug" in your code. If it's placed into the head section, then it's not gonna work (document.body...), however document.bgColor works fine.
Yet there's one "bug" in your code. If it's placed into the head section, then it's not gonna work (document.body...), however document.bgColor works fine.The bgColor property is deprecated for CSS. I was intending for it to be placed in the body, yes; I probably should have made that clearer.
jscheuer1
05-20-2007, 02:30 PM
I came up with a simpler looking solution:
document.body.style.backgroundColor = "#" + Math.floor(Math.random()*16777215).toString(16);
But, that doesn't always generate a valid css hex color value. If it was invalid though, the browser would just use the default for the page. But, this bothered me so, I:
var bgc = "#" + Math.floor(Math.random()*16777215).toString(16);
while(bgc.length!=4&&bgc.length<7)
bgc+='0';
document.body.style.backgroundColor = bgc;
We could wrap that up to protect the variable from interfering with other scripts or being interfered with:
(function(){
var bgc = "#" + Math.floor(Math.random()*16777215).toString(16);
while(bgc.length!=4&&bgc.length<7)
bgc+='0';
document.body.style.backgroundColor = bgc;
})();
These would all go after the opening body tag. But, this doesn't address the matter of inappropriate foreground color. So, I then went a little nuts and found this 'Class':
http://juicystudio.com/article/javascript-contrast-class.php
Which with minor adjustments to the min values was able to return black or white for the foreground color. This added to the weight of the code considerably. And while I was at it, I made the script write out a style declaration so that it could (even should) go in the head of the page, as well as taking care of link color:
<script type="text/javascript">
/*
Color Contrast | Andrew Waer
Origins: http://juicystudio.com/services/colourcontrast.php
Usage:
// Contrast test for two colors
// returns passing score OR false if test fails
Contrast.test('#ffffff', '#000000');
// find best match from one or two color sets
// returns array containing two hex values OR false if no match
Contrast.match('#ffffff', ['#000000', '#336699']);
Contrast.match(['#ffffff', '#000000', '#336699']);
Contrast.match(['#ffffff','#ffffcc'], ['#000000', '#336699']);
*/
var Contrast = function()
{
// private functions and properties
var _private =
{
min : {
'brightness': 100,
'difference': 250
},
brightness : function(rgb1, rgb2){
var b1 = ((rgb1.r * 299) + (rgb1.g * 587) + (rgb1.b * 114)) / 1000;
var b2 = ((rgb2.r * 299) + (rgb2.g * 587) + (rgb2.b * 114)) / 1000;
return Math.abs(Math.round(b1-b2));
},
difference : function(rgb1, rgb2){
var diff = (Math.max(rgb1.r, rgb2.r) - Math.min(rgb1.r, rgb2.r)) +
(Math.max(rgb1.g, rgb2.g) - Math.min(rgb1.g, rgb2.g)) +
(Math.max(rgb1.b, rgb2.b) - Math.min(rgb1.b, rgb2.b));
return Math.abs(Math.round(diff));
},
rgb : function(hex){
hex = hex.replace('#','');
var rgb = {
r: parseInt(hex[0] + hex[1], 16),
g: parseInt(hex[2] + hex[3], 16),
b: parseInt(hex[4] + hex[5], 16)
};
return rgb;
}
};
// public functions and properties
var _public =
{
test : function(hex1, hex2){
var rgb1 = _private.rgb(hex1);
var rgb2 = _private.rgb(hex2);
var brightness = _private.brightness(rgb1, rgb2);
var difference = _private.difference(rgb1, rgb2);
return (
brightness >= _private.min.brightness && difference >= _private.min.difference
? ((brightness - _private.min.brightness) + (difference - _private. min.difference))
: false
);
},
match : function(hex1, hex2){
var total_score, i, j;
if (typeof hex1 == 'string') {hex1 = [hex1];}
if (typeof hex2 == 'string') {hex2 = [hex2];}
var best_match = {
score: 0,
hex1: null,
hex2: null
};
if (hex2 == null){
for (i=0; i<hex1.length; i++){
for (j=0; j<hex1.length; j++){
total_score = _public.test(hex1[i], hex1[j]);
if (total_score > best_match.score){
best_match.score = total_score;
best_match.hex1 = hex1[i];
best_match.hex2 = hex1[j];
}
}
}
}
else {
for (i=0; i<hex1.length; i++){
for (j=0; j<hex2.length; j++){
total_score = _public.test(hex1[i], hex2[j]);
if (total_score > best_match.score){
best_match.score = total_score;
best_match.hex1 = hex1[i];
best_match.hex2 = hex2[j];
}
}
}
}
return (
best_match.score > 0
? [ best_match.hex1, best_match.hex2 ]
: false
);
}
};
return _public;
}();
(function(){
var fgc, f, bgc = "#" + Math.floor(Math.random()*16777215).toString(16);
while(bgc.length<7){
if(bgc.length==3)
bgc='#'+bgc.charAt(1)+'0'+bgc.charAt(2)+'0'+bgc.charAt(3)+'0';
else
bgc+='0';
}
fgc=(f = Contrast.match(bgc,['#000000','#ffffff'])[1])? f : 'black';
document.write('<style type="text\/css">\n\
body {\n\
color:'+fgc+';\n\
background-color:'+bgc+';\n\
}\n\
a {\n\
color:'+fgc+';\n\
}\n\
<\/style>')
})();
</script>
I think a much simpler solution is available for getting the contrast and will publish that soon if it works like I think it will.
Bob90
05-20-2007, 03:02 PM
Ha Ha Ha :D
The more I use DD the more I get to know the personalities.
That is a funny post. Very funny.
I sometimes think we all have too much time. ;)
Heh :)
I came up with a simpler looking solution:Yes, I posted this initially, but then looked again at the post and realised the OP was specifically asking for a random choice from a list of colours. You can express hexadecimal numbers in Javascript, by the bye: 0x1000000 is a lot easier to comprehend.
jscheuer1
05-20-2007, 08:30 PM
Apparently I misunderstood both the OP and the 'Class' I had found. In any event, the fix is in, in so far as producing a random background color with a legible foreground color and links (some of the color combinations of my long version weren't as legible as they should be). And, it is much shorter code (goes in the head after any style declarations):
<script type="text/javascript">
/* Random Colors © John Davenport Scheuer
* as first seen in www.dynamicdrive/forums/
* username: jscheuer1
* This credit must remain for legal use */
(function(){
var fgc, bcg_bright;
for (var i = 0, bgc_rgb = []; i < 3; i++)
bgc_rgb[i] = Math.floor( Math.random() * 255 );
bcg_bright = ( bgc_rgb[0] * 299 + bgc_rgb[1] * 587 + bgc_rgb[2] * 114 ) / 1000;
fgc = bcg_bright > 127? 'black' : 'white';
if ( fgc == 'white' )
while ( 765 - bgc_rgb[0] - bgc_rgb[1] - bgc_rgb[2] < 500 ){
i = i < 2? i + 1 : 0;
bgc_rgb[i] = bgc_rgb[i] > 0? bgc_rgb[i] - 1 : bgc_rgb[i];
}
else
while ( bgc_rgb[0] + bgc_rgb[1] + bgc_rgb[2] < 500 ){
i = i < 2? i + 1 : 0;
bgc_rgb[i] = bgc_rgb[i] < 255? bgc_rgb[i] + 1 : bgc_rgb[i];
}
document.write ('\n<style type="text\/css">\n\
body {\ncolor:'+fgc+';\n\
background-color:rgb('+bgc_rgb.join(',')+');\n\
}\na {\ncolor:'+fgc+';\n}\n<\/style>')
})();
</script>
Note: Thanks to:
http://www.w3.org/TR/2000/WD-AERT-20000426#color-contrast
for explaining a possible mathematical basis for color contrast.
Also: If you have conflicting styles, you may need to get rid of them or augment the document.write section of the script to compensate.
thehealey
05-23-2007, 05:45 PM
Thanks, I think. Looks scary.
thehealey
05-29-2007, 04:45 PM
Sorry to double post but I'd figured you might want to see your work in action. So if you click here (http://www.picturehouse.co.nr/) then follow the menu to one of the actual videos, there’s your coding.
I decided to go with Twey's code because I could have more control of the colours, I didn't want the colours to be to bright. I was going to use the code on the index page as well but that blue just got the better of me.
Powered by vBulletin® Version 4.2.2 Copyright © 2021 vBulletin Solutions, Inc. All rights reserved.