Home > Net >  How can I change an elements color when clicked a second time?
How can I change an elements color when clicked a second time?

Time:08-05

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';
});

CodePudding user response:

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>

CodePudding user response:

you can follow this steps

First let's take a counter variable

let clickCount = 0;

Then add click event.Hare is your code:

const btn = document.getElementById("like");
    
            let clickCount = 0;
            btn.addEventListener("click", () => {
                clickCount  ;
    
                if (clickCount > 1) {
                    btn.style.color = "red";
                }
            });
<button id="like">Like</button>

  • Related