I wrote another click but it didn't work
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:
var isClicked = false;
$("#green").click(function() {
var audio = new Audio('sounds/green.mp3');
audio.play();
if (isClicked) {
$("#green").css("background-color", "green");
$("#green").css("border", "0px");
} else {
$("#green").css("background-color", "gray");
$("#green").css("border", "20px solid white");
}
isClicked = !isClicked;
});
Each click does three things:
- Play the audio
- Conditionally change CSS one way or another
- Toggle the
isClicked
so that the next click will choose the other condition
We could take this a step further though. Since what you're toggling are CSS styles, use CSS (instead of JavaScript) to define those styles. For example, suppose you have these styles:
#green {
background-color: green;
border: 0px;
}
#green.active {
background-color: gray;
border: 20px solid white;
}
Then all you'd need to toggle is the active
class on the element. And conveniently enough, jQuery has a method to do that without having to track state in a variable. So your JavaScript code simplies to:
$("#green").click(function() {
var audio = new Audio('sounds/green.mp3');
audio.play();
$("#green").toggleClass("active");
});