This content originally appeared on Envato Tuts+ Tutorials and was authored by Jemima Abu
In this tutorial you’ll learn how to change the background color of a page randomly, using JavaScript. You’ll also learn how to modify your code using HSL color values to generate only pastel colors or dark colors.
Let’s take a look at what we’ll be building:
In this demo, we change the background color and text color of the page every 1500ms. Most of the heavy lifting is done with JavaScript but let’s take a look at the content and styling:
HTML
For the content of our page, we’ll create an element with an id background
and put some text in it.
<main id="background"> <h1> Generate Random Background Colors with JavaScript </h1> </main>
CSS
We’ll use CSS to control the background-color
transition so the change looks smoother.
main { transition: background 1s; }
JavaScript
We’ll be generating random colors in JavaScript by combining these two methods:
- HSL color notation, and
- The
Math
library
“The
hsl()
functional notation expresses a given color according to its hue, saturation, and lightness components” - MDN
The hue value has a maximum of 360 and represents the degree of the color position on a color wheel. The saturation and lightness values have a maximum of 100 and represent the percentage saturation and lightness of a color respectively.
Fiddle with the ranges below to see how the Hue, Saturation and Lightness values affect how a color looks.
In order to generate completely random colors, we’ll pass random numbers within a fixed range to the three HSL values. We can do this using Math.random
and Math.floor
Math.random
generates random numbers between 0 and 1. We can multiply these numbers by our specified range and use Math.floor
to round up to the nearest whole number.
const getRandomNumber = (maxNum) => { return Math.floor(Math.random() * maxNum); };
Then we’ll use the getRandomNumber
function to generate random values for our HSL notation.
const getRandomColor = () => { const h = getRandomNumber(360); const s = getRandomNumber(100); const l = getRandomNumber(100); return `hsl(${h}deg, ${s}%, ${l}%)`; };
Finally, we pass the random generated color to our background element.
const setBackgroundColor = () => { const randomColor = getRandomColor(); document.getElementById("background").style.backgroundColor = randomColor; }
This allows us to set a random color to our background.
Applying the New Color
We can decide whether to change the background color whenever the user loads the page or regularly at a set interval by passing the above code into an onLoad
or a setInterval
function.
window.onload = () => { setBackgroundColor() };
setInterval(() => { setBackgroundColor(); }, 1500);
Here’s the completed JavaScript code:
const background = document.getElementById("background"); const getRandomNumber = (maxNum) => { return Math.floor(Math.random() * maxNum); }; const getRandomColor = () => { const h = getRandomNumber(360); const s = getRandomNumber(100); const l = getRandomNumber(100); return `hsl(${h}deg, ${s}%, ${l}%)`; }; const setBackgroundColor = () => { const randomColor = getRandomColor(); background.style.backgroundColor = randomColor; background.style.color = randomColor; }; setBackgroundColor(); setInterval(() => { setBackgroundColor(); }, 1500);
In the above demo, we can see that the text color also changes randomly but in an inverted manner to keep it readable against the background. This is done using CSS.
Invert Text Colors with CSS
First, we pass the same color as the background for the text color in our setBackgroundColor
function.
const setBackgroundColor = () => { const randomColor = getRandomColor(); background.style.backgroundColor = randomColor; background.style.color = randomColor; };
Then we use the CSS invert filter to make sure the text color is contrasted against the background.
h1 { -webkit-filter: invert(100%); filter: invert(100%); transition: color 1s; }
How to Randomly Generate Pastel Colors
One benefit to using HSL color values is that we can control how saturated or bright the randomly generated colors are. In this way we can modify our code to generate only pastel colors.
We do this by setting a fixed value of 100% to the saturation and a value of 90% to the lightness. Our updated code looks like this:
const getRandomPastelColor = () => { const h = getRandomNumber(360); return `hsl(${h}deg, 100%, 90%)`; };
How to Randomly Generate Dark Colors
We can apply the same logic to generate darker colors.
const getRandomDarkColor = () => { const h = getRandomNumber(360); return `hsl(${h}deg, 50%, 10%)`; };
Conclusion
This tutorial has primarily taught you how to generate random colors with JavaScript, but it should also have given you a good grasp on the HSL notation for colors, and using the Math library for generating numbers.
Feel free to apply this to a project you’re working on to spruce up your page!
Learn JavaScript Skills
We have a wide range of beginner to intermediate level JavaScript tutorials, teaching you foundational knowledge and practical skills.
- CSSSwitch Between Color Schemes with CSS Variables and JavaScript
- JavaScriptHow to Build a Reading Progress Bar With CSS and JavaScript
- Scroll EventsHow to Animate on Scroll With Vanilla JavaScript
- HTMLBuild a Simple Weather App With Vanilla JavaScript
- JavaScriptAn Introduction to JavaScript Event Listeners for Web Designers
- JavaScriptHow to Implement Debounce and Throttle with JavaScript
- JavaScriptHow to Build a JavaScript Popup Modal From Scratch
This content originally appeared on Envato Tuts+ Tutorials and was authored by Jemima Abu
Jemima Abu | Sciencx (2021-05-31T07:44:37+00:00) How to Generate Random Background Colors With JavaScript. Retrieved from https://www.scien.cx/2021/05/31/how-to-generate-random-background-colors-with-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.