RandomColor Example -- Source Code
HTML Page -- index.htm
<!DOCTYPE html>
<!-- RandomColor Example
Source code file: index.htm
When button is clicked, show a color with
random rgb components. -->
<html>
<head>
<meta content="text/html; charset=utf-8"
http-equiv="Content-Type">
<title>RandomColor Example</title>
<link rel="stylesheet" type="text/css" href="styles.css">
<script src="script.js"></script>
</head>
<body>
<h1>RandomColor Example</h1>
<button id="btn1">
Show Random Background Color
</button><br><br>
<img id="img1">
</body>
</html>
CSS Page -- styles.css
/* RandomColor Example
Source code file: styles.css */
body { background-color: #e0e0e0;
color: #000060;
font-family: Verdana, Arial, sans-serif; }
/* Set initial background color of image to black */
img { width: 200px; height: 200px;
background-color: #000000; }
Script Page -- script.js
// ShowRandomColor Example
// Source code file: script.js
// When button is clicked, change background
// color of image to a color with random rgb components.
function getRandomColor( ) {
// Get random color components.
var r = Math.floor(Math.random( ) * 256);
var g = Math.floor(Math.random( ) * 256);
var b = Math.floor(Math.random( ) * 256);
// Convert color components to hex.
var rHex = r.toString(16).padStart(2, "0");
var gHex = g.toString(16).padStart(2, "0");
var bHex = b.toString(16).padStart(2, "0");
// Combine color components to obtain
// hex color code.
return `#${rHex}${gHex}${bHex}`;
}
// Display random background color in image.
function displayColor( ) {
var img = document.getElementById("img1");
img.style.backgroundColor = getRandomColor( )
}
// Attach event listener to button.
function init( ) {
var button1 = document.getElementById("btn1");
button1.addEventListener("click", displayColor);
}
// Run init method after page loads.
window.addEventListener("load", init);