Dhruv Chadha Dhruv Chadha - 5 months ago 9
CSS Question

Remove changes from one element when event occurs on another element?

In this program, clicking any box changes its color. However I want that on clicking one box, its color changes but on clicking the other box, its color should change but color from first box should disappear (ie return back to original state).

In a wider perspective, how can i return an element back to its original state once the event occurs on another element. (just like what happens when we add

:hover
effects in css, and the element returns to its original state when we remove mouse from it)

EDIT - In my original project, I have lots of divs with similar click effects. I want a general method that event on one element leads to removing all changes from all other elements.



var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
div1.addEventListener("click", function() {this.style.backgroundColor="red";});
div2.addEventListener("click", function() {this.style.backgroundColor="red";});

div {
width: 100px;
height: 100px;
margin: 10px;
border: 1px solid black;
}

<html>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>




Answer

In any case give the DIVS a class

Plain JS

window.onload = function() {
  [].map.call(document.querySelectorAll('.toggle'), function(el) {
    el.onclick = function() { // attach the handler
      [].map.call(document.querySelectorAll('.toggle'), function(el) {
        el.classList.remove('active'); // remove from all
      });
      this.classList.add('active'); // add on current
    }
  });
}
div {
  width: 100px;
  height: 100px;
  margin: 10px;
  border: 1px solid black;
}
.active {
  background-color: red
}
<html>

<body>
  <div class="toggle" id="div1"></div>
  <div class="toggle" id="div2"></div>
</body>

</html>

jQuery in case you want to try it:

$(function() {
  $('.toggle').on("click",function() {
    $('.toggle').removeClass("active"); // could add .not(this) here
    $(this).addClass("active");
  });
});
div {
  width: 100px;
  height: 100px;
  margin: 10px;
  border: 1px solid black;
}
.active {
  background-color: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>

<body>
  <div class="toggle" id="div1"></div>
  <div class="toggle" id="div2"></div>
</body>

</html>