When I define a code to click and change that element again, I want the element to return to the first state with another click
I wrote another click but it didn’t work
The toggle didn’t work properly either
I want css to appear when clicked and css to be removed when clicked again
$("#green").click(function() {
var audio = new Audio('sounds/green.mp3');
audio.play();
$("#green").css("background-color", "gray");
$("#green").css("border", "20px solid white");
});
$("#green").click(function() {
var audio = new Audio('sounds/green.mp3');
audio.play();
$("#green").css("background-color", "green");
$("#green").css("border", "0px");
});
2
Answers
I’d wager that both of the click handlers worked just fine, they simply cancel out the overall result because they both run on every click.
You only need one click handler, it just needs to conditionally perform one operation vs. another. One way to maintain that condition is to store in some global state which operation was last performed. For example:
Each click does three things:
isClicked
so that the next click will choose the other conditionJust set up the two different styles as classes and one click event that toggles between them. You just need to be careful that the secondary style is written with a selector that is more specific than the default so that it will override when applied.