I’m working on a like button for a website I’m making and I have a simple piece of JavaScript that changes the color to red when it is clicked, but how can I make the color alternate so if you click it again it goes back to black than changes to red again if you click it another time etc.
const btn = document.getElementById("like");
btn.addEventListener('click', function onClick() {
btn.style.color = 'crimson';
});
>Solution :
Use the toggle method of the classList.
And, as a general rule, you should strive to avoid setting an "inline style" (element.style.xxx = xxx) as this creates a style for the element that can only be overridden by another inline style, leads to duplication of code, and therefore code that doesn’t scale well. Instead, always try to work with CSS classes.
document.getElementById("like").addEventListener('click', function() {
this.classList.toggle("active");
});
.active { color:crimson; }
<button id="like">Like</button>