Programming Forum

Please login or register.

Login with username, password and session length
Advanced search  

News:

Author Topic: Color  (Read 4034 times)

Brady

  • Guest
Color
« on: June 08, 2008, 12:11:28 AM »

How do you make a background page color change randomly in PHP?
Logged

Mark

  • Administrator
  • Newbie
  • *****
  • Posts: 1
    • View Profile
    • EntryLevelProgrammer.com
    • Email
Re: Color
« Reply #1 on: June 08, 2008, 12:18:26 AM »

Here is one way you can randomly change the background color in PHP.

Code: [Select]
<?php
print "<html>\n";
$intRed rand(0,255); // generates a random number between 0 and 255
$intGreen rand(0,255);
$intBlue rand(0,255);
$hexRed dechex($intRed+0); // converts the number to hex
$hexGreen dechex($intGreen+0);
$hexBlue dechex($intBlue+0);
$strRed=$hexRed;
// makes the value two characters wide so red, green, and blue each take two characters in the RGB value
if (strlen($strRed) == 1) { $strRed="0".$strRed; }
$strGreen=$hexGreen;
if (
strlen($strGreen) == 1) { $strGreen="0".$strGreen; }
$strBlue=$hexBlue;
if (
strlen($strBlue) == 1) { $strBlue="0".$strBlue; }
$hexRGB=$strRed.$strGreen.$strBlue// joins the three string vales to make a RGB value
print "<body bgcolor=$hexRGB>\n";
print 
"The background page color is $hexRGB\n";
print 
"</body>\n";
print 
"</html>\n";
?>

« Last Edit: December 08, 2011, 12:25:14 AM by Mark »
Logged

Brady

  • Guest
Re: Color
« Reply #2 on: January 24, 2012, 02:14:02 AM »

How do you make the background color change randomly in JavaScript?
Logged

Mark

  • Administrator
  • Newbie
  • *****
  • Posts: 1
    • View Profile
    • EntryLevelProgrammer.com
    • Email
Re: Color
« Reply #3 on: January 24, 2012, 02:18:18 AM »

Here is one way to do it in JavaScript.

Code: [Select]
<html>
<body>
<script type="text/javascript">
var intRed=Math.floor(Math.random()*256) // generates a random number between 0 and 255
var intGreen=Math.floor(Math.random()*256)
var intBlue=Math.floor(Math.random()*256)
var strHexRed = intRed.toString(16); // converts the number to hex
var strHexGreen = intGreen.toString(16);
var strHexBlue = intBlue.toString(16);
// make the value two characters wide so red, green, and blue each take two characters in the RGB value
if (strHexRed.length == 1) { strHexRed="0"+strHexRed; }
if (strHexGreen.length == 1) { strHexGreen="0"+strHexGreen; }
if (strHexBlue.length == 1) { strHexBlue="0"+strHexBlue; }
var strRGB=strHexRed+strHexGreen+strHexBlue; // joins the three string vales to make a RGB value
document.body.bgColor=strRGB;
document.write("The background page color is "+strRGB+"\n");
</script>
</body>
</html>
« Last Edit: January 24, 2012, 02:33:37 AM by Mark »
Logged
 


www.entrylevelprogrammer.com