<!DOCTYPE html>
<html>
<head>
<style>
#colorBox {
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div id="colorBox"></div>
<button id="toggleColorButton">Toggle Color</button>
<script>
const colorBox = document.getElementById("colorBox");
const toggleColorButton = document.getElementById("toggleColorButton");
toggleColorButton.addEventListener("click", () => {
if (colorBox.style.backgroundColor === "red") {
colorBox.style.backgroundColor = "blue";
} else {
colorBox.style.backgroundColor = "red";
}
});
</script>
</body>
</html>
The first time a user clicks the button, the color of the box will stay red. This is because the style property only returns inline styles, not styles from a stylesheet. In order to get the computed style of an element, you can use the getComputedStyle function. However this leads us to another potential bug: the backgroundColor property returns the color in the format rgb(255, 0, 0) instead of red.
To fix this, you can compare the computed color to the RGB value of red.
<html>
<head>
<style>
#colorBox {
width: 100px;
height: 100px;
background-color: red;
}
</style>
</head>
<body>
<div id="colorBox"></div>
<button id="toggleColorButton">Toggle Color</button>
<script>
const colorBox = document.getElementById("colorBox");
const toggleColorButton = document.getElementById("toggleColorButton");
toggleColorButton.addEventListener("click", () => {
const computedStyle = getComputedStyle(colorBox);
const currentColor = computedStyle.backgroundColor;
if (currentColor === "rgb(255, 0, 0)") {
colorBox.style.backgroundColor = "blue";
} else {
colorBox.style.backgroundColor = "red";
}
});
</script>
</body>
</html>