How to use JavaScript to change CSS for multiple elements

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.

+4
source share
4 answers

Another similar but simpler way to do this is: jsBin ;)

var H4 = document.getElementsByClassName("test"), act;

[].forEach.call(H4, function(el){
    el.addEventListener("click", function(){
       if(act) act.classList.remove("active");
       return (this.classList.toggle("active"), act=this);
    });
});
+1
source

Yes, pretty simple.

Assumptions

  • You are not trying to support IE8 because you are using classList
  • , DOM.

JSBin

JavaScript, , :

var techs = [].slice.call(document.querySelectorAll('#pTwoRowOne h4'));

function set_active(event) {
  techs.forEach(function(tech){
    if (event.target == tech) { return; }
    tech.classList.remove('active');
  });
  event.target.classList.toggle('active');
}

techs.forEach(function(item) {
  item.addEventListener('click', set_active);
});

[].slice.call(document.querySelectorAll('#pTwoRowOne h4')); - , NodeList Array. forEach . querySelectorAll NodeList, , CSS. , CSS- .

addEventListener , add onclick +=, . ( ) ECMA5 .

, DOM , . JavaScript , , .

JS, .

+4

Assuming you have only one active element, you can find it with document.querySelector()- if you can have multiplicity, you can use document.querySelectorAll()and scroll through them.

Simple case:

function activate(event) {
  var active=document.querySelector('.active');

  // activate the clicked element (even if it was already active)
  event.target.classList.add('active');

  // deactivate the previously-active element (even if it was the clicked one => toggle)
  if (active) active.classList.remove('active');
}

document.getElementById("techBio").addEventListener("click",activate);
document.getElementById("techCart").addEventListener("click",activate);
document.getElementById("techChem").addEventListener("click",activate);
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;
}
<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>
Run codeHide result
+3
source

You can do something like this:

[].slice.call(document.querySelectorAll(".test")).forEach(function(element) {
  element.addEventListener('click', function(event) {
    if (activeElement = document.querySelector(".test.active")) {
      activeElement.classList.remove("active");
    };
    event.target.classList.add('active');
  });
});

Basically, first we remove the class activefrom the active element, then add it to the target.

Jsbin

+1
source

All Articles