Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Clicking on jQuery

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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:

  1. Play the audio
  2. Conditionally change CSS one way or another
  3. Toggle the isClicked so that the next click will choose the other condition
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading