Tuesday, 24 December 2019

Webpage background colour changer

The following JavaScript code is designed to randomly change the background colour of the webpage each time it is refreshed.
Screenshot of webpage colour
Screenshot of webpage colour

We start by creating an 'array' of different colours we want to use for the webpage background.
var bgColour = ["#029FD4", "#D43702", "#1EFF00", "#EAEAFF", "#FFEA00", "#AB5252", "#FFFFFF", "#DE28D8"];
Next we make use of 'Math.random()' to generate a random number greater than or equal to 0.0 and less than 1.0 and we multiply this by the length of the above array (so 8 in this instance).
var arrayPosition = Math.random() * bgColourLength;
From this we get a random number that contains multiple decimal places, so we can use 'Math.floor()' to round to the nearest whole number.
var roundNumber = Math.floor(arrayPosition);
Now we can change the webpage background colour by using the randomly generated whole number as the index position in the colour array.
document.body.style.background=bgColour[roundNumber];

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="author" content="Phil Bainbridge">
<meta name="viewport" content="width-device-width, initial-scale=1.0">
<title> Background Colour Changer </title>
</head>
<body>
<h2> Refresh the page to randomly change the colour. </h2>
<script>
// array of different background colours to use (hexadecimal)
var bgColour = ["#029FD4", "#D43702", "#1EFF00", "#EAEAFF", "#FFEA00", "#AB5252", "#FFFFFF", "#DE28D8"];
// length of array for below multiplication to generate a random number
var bgColourLength = bgColour.length;
// 'Math.random()' generates a random number greater than or equal to 0.0 and less than 1.0
var arrayPosition = Math.random() * bgColourLength;
// 'Math.floor()' rounds the above result to the nearest whole number
var roundNumber = Math.floor(arrayPosition);
// a random index number in the array is selected and applied as the background colour to the webpage
document.body.style.background=bgColour[roundNumber];
</script>
</body>
</html>
Webpage background colour changer.html

No comments:

Post a Comment