jQuery on and off events but same button

40 Views Asked by At

I want to make a button that, when pressed, changes the background color of my page. Then, when you press it again, the page will go back to its original color. I don't understand how to make it go back to the original color again (using Toggle switch).


$(function () {
    $("#button").click(function () {
        $("p").css("background-color", "red");
    });
});
1

There are 1 best solutions below

0
David On BEST ANSWER

Ideally you would use classes for this, which are easily toggled. For example:

$(function () {
  $("#button").click(function () {
    $("p").toggleClass("red");
  });
});
.red {
  background-color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Test</p>
<button id="button" type="button">Click</button>


If you must use direct style rules then one approach is to store the original value somewhere. Then in the click handler just compare the current value with that original and change it one way or the other. For example:

$(function () {
  const original = $("p").css("background-color");
  
  $("#button").click(function () {
    const current = $("p").css("background-color");
    if (current === original) {
      $("p").css("background-color", "red");
    } else {
      $("p").css("background-color", original);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Test</p>
<button id="button" type="button">Click</button>