I would like to have the following scenario:
- only one div can be selected at the time (DONE)
- by click on the div it should be selected and other divs should stay unselected (DONE)
- by click on the already selected div, that div should be unselected and other divs will stay also unselected(TO DO)
I'm having problem to implement the last feature where by click on the already selected div to unselect it and other already working features should work as before. Could someone help me to make it work ?
var x = document.getElementsByClassName('optionsecoptions')
for (var i = 0; i < x.length; i++) {
x[i].addEventListener("click", function() {
var selectedEl = document.querySelector(".selected");
if (selectedEl) {
selectedEl.classList.remove("selected");
}
this.classList.add("selected");
}, false);
}
.optionsecoptions {
width: 400px;
padding-left: 10px;
height: 40px;
background: #bbb8b8;
float: left;
font-size: 20px;
cursor: pointer;
}
.optionsecoptions:hover,
.optionsecoptions:active {
background-color: #226fa3;
transition: background-color 0.4s ease-in, border-color 0.4s ease-in;
color: #ffffff;
}
.selected {
background-color: #226fa3;
transition: background-color 0.4s ease-in, border-color 0.4s ease-in;
color: #ffffff;
}
<div style="margin-top:10px;">
<div class="optionsecoptions">
Computers
</div>
<div class="optionsecoptions" style="top:151px;">
Electronics
</div>
<div class="optionsecoptions" style="top:212px;">
Mechanical
</div>
<div class="optionsecoptions" style="top:273px;">
Electrical
</div>
</div>