👨💻 Daily Code 49 | Change the Background Color with 🟨JavaScript
Gregor Schafroth
Posted on January 25, 2024
Alright! Since I want to practice more JavaScript HTML manipulation I asked ChatGPT for an other exercise to do exactly that. Here is what I got, and below as always my attempt to solve it
Exercise: Change the Background Color with JavaScript
-
HTML Setup: Create an HTML file with a
<div>
element. Give this<div>
anid
so you can easily target it with JavaScript. Inside the<div>
, put some text like "Hello, world!" -
JavaScript Task: Write a JavaScript function that changes the background color of this
<div>
to a color of your choice. -
Triggering the Change: Attach a button to the HTML. When this button is clicked, it should execute your JavaScript function, changing the background color of the
<div>
. -
Extra Challenge: If you want to take it a step further, create a text input where you can type in a color, and upon clicking the button, the background color of the
<div>
changes to whatever color you typed in.
This exercise will help you understand how JavaScript can interact with HTML elements and respond to user events. Enjoy coding!
My Code
I think I start grasping this well now. The only thing is I didn’t know how to actually set a background color, so for two lines I had to ask ChatGPT for help.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Exercise: Change the Background Color with JavaScript</title>
</head>
<body>
<input id="js-input" placeholder="Color" type="text">
<button id="js-button">Change Background Color</button>
<div id="js-div">[color]</div>
<script>
document.getElementById('js-button').onclick = function () {
document.getElementById('js-div') /* ... I am not sure how to continue here */
}
</script>
</body>
</html>
And below is the completed solution.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Exercise: Change the Background Color with JavaScript</title>
</head>
<body>
<input id="js-input" placeholder="Color" type="text">
<button id="js-button">Change Background Color</button>
<div id="js-div">[color]</div>
<script>
document.getElementById('js-button').onclick = function () {
let color = document.getElementById('js-input').value;
document.getElementById('js-div').style.backgroundColor = color;
}
</script>
</body>
</html>
What I learned:
-
.value
is what I need to use to extract a text from an input field -
.style.backgroundColor
is how to set the background color.
Looks like .style
is the general way to manipulate 🟦CSS
Alright this was great. Will do a few more of these next!
💖 💪 🙅 🚩
Gregor Schafroth
Posted on January 25, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.