Is there a way for me to write less lines of codes for this function? I want it so that when you press either one of the buttons it will alternate between the two colors. function green() is the exact opposite of red.
<h1 id="header">Red Or Green</h1>
<button id="redButton" onclick="red()">Red</button>
<button id="greenButton" onclick="green()">Green</button>
function red() {
document.getElementById("header").innerHTML = "Red"
document.getElementById('header').style.color = "red"
document.getElementById('redButton').style.color = "white"
document.getElementById('redButton').style.backgroundColor = "red"
document.getElementById('greenButton').style.color = "black"
document.getElementById('greenButton').style.backgroundColor = "grey"
}
5
Answers
You can try passing the color, based on which you can setting the styles like the following way:
You can create CSS classes instead and you can add and remove them based on your requirement.
The following can be created:
maybe something like this:
with a
<div id="buttons-group">
For a DRY solution have one event handler that covers both button click events.
addEventListener
.classList
.