I made a button and added event listener for click to it. right now I set the following code for JS (button id is next):
next.addEventListener("click", () => {
if (AB.style.backgroundColor === "pink") {
AB.style.backgroundColor = "red";
} else if (AB.style.backgroundColor === "red") {
AB.style.backgroundColor = "orange";
}
});
#AB {
background-color: pink;
}
<div id="AB">Words</div>
<button id="next">Button</button>
Now when I click the button the first time, the color does change from pink to red. However, the second click (namely the else if part) does not do anything. How can I make the color toggle on click?
Yep, as suggested @ggorlen Look into getComputedStyle().
But it will give you a computed value, which is in rgb(,,,) format.
I'd recommend using classes instead.
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.pink {
background-color: pink;
}
.red {
background-color: red;
}
.orange {
background-color: orange;
}
</style>
</head>
<body>
<div id="AB" class="pink">Words</div>
<button id="next">Button</button>
</body>
<script>
next.addEventListener("click", () => {
const element = document.getElementById('AB');
if (element.classList.contains('pink')) {
element.classList.remove('pink');
element.classList.add('red');
} else if (element.classList.contains('red')) {
element.classList.remove('red');
element.classList.add('orange');
}
});
</script>
</html>
The problem here is that it seems that your div does not have any style.backgroundColor value by default.
To face this problem you can set the backgroundColor value dynamically when the javascript is loaded.
AB.style.backgroundColor = "pink"
next.addEventListener("click", function () {
if (AB.style.backgroundColor === "pink") {
AB.style.backgroundColor = "red";
} else if (AB.style.backgroundColor === "red") {
AB.style.backgroundColor = "orange";
}
});
<div id="AB">Words</div>
<button id="next">Button</button>
As ggorlen commented you can get the style by using the getComputedStyle() and then compare it against the CSS background-color property. Check out getComputedStyle on MDN.
next.addEventListener("click", () => {
if (getComputedStyle(AB).getPropertyValue("background-color") === "rgb(255, 192, 203)") {
AB.style.backgroundColor = "red";
} else if (AB.style.backgroundColor === "red") {
AB.style.backgroundColor = "orange";
}
});
#AB {
background-color: pink;
}
<div id="AB">Words</div>
<button id="next">Button</button>