Dynamically change styles using JavaScript
Another simple app that changes the background color of elements clicked on
By: Ajdin Imsirovic 24 November 2019
In this article, we’ll write another simple app in JavaScript. This one will allow the user to click an element and update that element’s background color randomly.
Image by CodingExercises
What we’ll be building
We’ll just use our JavaScript console for this quick exercise. The goal is simple: we want to color the background of the body element via JavaScript console.
Here’s the code:
document.body.style.background = "yellow"
Obviously, running this code will change the background of the body
element of our page.
We can further improve this by getting the color as an input from the user, using the prompt()
function.
For example:
var givenColor = prompt('Type in an HTML named color (such as orange, green, blue, etc.');
document.body.style.background = givenColor;
That’s it for this simple exercise in JavaScript.