mildrenben
mildrenben

Reputation: 3757

Add/remove class from element depending on whether another element has the class

Say I have 4 boxes and the user needs to select one.

I want to apply an active class to the box that the user has clicked. But if the user clicks another box, I want to remove the class from the first clicked box and add it to the second clicked box.

The below code doesn't work - anyone know why? Even if the below code ran the way I would expect it to, it still wouldn't be checking the other boxes around it to see if they have the active class before adding/removing.

html:

<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

css:

.box {
  background: green;
  height: 100px;
  width: 100px;
  display: inline-block;
  padding: 10px;
  margin: 30px 50px;
}

.active {
  outline: solid 5px aqua;
}

js:

var box = document.getElementsByClassName('box');

for(var i = 0; i < box.length; i++){
  box[i].addEventListener('click', function(){
        if(box[i].classList.contains('active')){
      box[i].classList.remove('active');
    }
    else {
      box[i].classList.add('active');
    }
  })
}

Upvotes: 0

Views: 2489

Answers (3)

Cyclonecode
Cyclonecode

Reputation: 29991

You first need to remove the active class for all elements and then use this.classList.add('active') after the loop, since you only would like to set the active class on the currently clicked element:

for(var i = 0; i < box.length; i++){
  box[i].addEventListener('click', function(){
    // remove active class for all elements
    for(var i = 0; i < box.length; i++) {
       box[i].classList.remove('active');
    }
    // add active to clicked element
    this.classList.add('active');
  });
}

Upvotes: 4

sideroxylon
sideroxylon

Reputation: 4416

If you can use jquery, this works:

$('.box').click(function() {
  $(this).addClass('active');
  $('.box').not(this).removeClass('active');
});
.box {
  background: green;
  height: 100px;
  width: 100px;
  display: inline-block;
  padding: 10px;
  margin: 30px 50px;
}
.active {
  outline: solid 5px aqua;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

Upvotes: 2

You Old Fool
You Old Fool

Reputation: 22941

How about:

$(".box").on("click", function() {
    $(".box").removeClass("active");
    $(this).addClass("active");
});

It's not pure javascript but should do what you want

Upvotes: 0

Related Questions