I am trying to use JavaScript to change the background color of an element after selecting it, and also make sure that only one element at a time has a specific background color. As soon as the user selects another item, I would like the previous item to be selected to replace with a different background color. Currently, I can only switch individual items by selecting an EACH item. I need to be able to select an element and apply a new background color, and then change the background color of the previous active element to a different color (one click).
What I'm trying to do is very similar to modern navbars or list items, where only one item at a time is “active” and has a background color different from other items in the same div, row, etc.
Notes on my work I use bootstrap and do not want to use jQuery for this particular project.
CSS
<!DOCTYPE html>
<html lang="en">
<head>
<style>
h4 {
border: 1px solid black;
border-radius: 8px;
padding: 10px 2px 10px 2px;
margin: 20px 20px 0px 20px;
background-color: #F0F0F0;
border-color: #F8F8F8;
color: #505050;
cursor: pointer;
}
.active {
background-color: #99E6FF;
}
</style>
</head>
</html>
HTML:
<div id="pTwoRowOne">
<div class="row">
<div class="col-md-4 row row-centered">
<h4 id="techBio" class="test">Biology</h4>
</div>
<div class="col-md-4 row row-centered">
<h4 id="techCart" class="test">Cartography</h4>
</div>
<div class="col-md-4 row row-centered">
<h4 id="techChem" class="test">Chemistry</h4>
</div>
</div>
</div>
JavaScript:
document.getElementById("techBio").onclick=function() {
document.getElementById("techBio").classList.toggle('active');
}
document.getElementById("techCart").onclick=function() {
document.getElementById("techCart").classList.toggle('active');
}
document.getElementById("techChem").onclick=function() {
document.getElementById("techChem").classList.toggle('active');
}
An example can be seen here: http://jsbin.com/fugogarove/1/edit?html,css,js,output
If I need to clarify, let me know.
source
share