t4d_ t4d_ - 1 year ago 79
jQuery Question

only one element at time can be "toggleClass"-ed in jQuery

How I am able to toggleClass on elements, but only one can be "toggled" at time.
There is solution (by adding another for loop to disable effect), but in pureJS and I need help to get this work in jQuery.



var elements = document.querySelectorAll("#box");

for ( var i = 0; i < elements.length; i++ ) (function(i){
elements[i].onclick = function() {
for (var j = 0; j < elements.length; j++) {
elements[j].style.border = '';
elements[j].innerHTML = '';
}
elements[i].style.border = "10px solid red";
elements[i].innerHTML = "selected";
};
})(i);

body {background-color: black;}
#box {
background: white;
color: red;
text-align: center;
box-sizing: border-box;
width: 100px;
height: 100px;
display: block;
float: left;
margin: 1%;
}
#box.red{
background: red;
}

<body>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
</body>





And here is jQuery function. In-short, I need that only one box can be red at time and when another is clicked it disable selected one. Exactly like one above in javascript.



$("div#box").click(function(){
$(this).toggleClass("red");
});

body {background-color: black;}
#box {
background: white;
color: red;
text-align: center;
box-sizing: border-box;
width: 100px;
height: 100px;
display: block;
float: left;
margin: 1%;
}
#box.red{
background: red;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>
<div id="box"></div>

</body>




Answer Source

The usual way to do this is to remove the class on all of the other possible 'toggles' before applying the class to the newly selected one, like this:

var boxes = $('div.box');

boxes.click(function(){
  boxes.removeClass('red');
  $(this).addClass('red');  
});

(You should use a class, not an ID any time you have more than one element to apply it to (so I've used .box, not #box).

Another important point is to select the boxes only once, and store them in a variable outside of the click handler. That way, you're not always re-selecting them on every click.