Skip to content
Advertisement

How can I repeatedly change the background style of a div using a click event in Javascript?

I am trying to change the background property of each day on a calendar, when clicked, between blue and green using javascript and CSS. like a toggle function. The default color is blue, and I’ve managed to get each day to turn green when clicked but I can’t figure out how to change them back to blue.

Here’s what I’ve tried.

const days = document.getElementsByClassName('day')

for (let i = 0; i < days.length; i++) {
  days[i].addEventListener('click', function(e) {
    if (e.target.style.background != 'linear-gradient(#7ce8b6, #00ff2a)') {
      e.target.style.background = 'linear-gradient(#7ce8b6, #00ff2a)'
    } else if (e.target.background != 'linear-gradient(#7CB9E8, #00FFFF)') {
      e.target.background = 'linear-gradient(#7CB9E8, #00FFFF)'
    }
  });
}
.day {
  height: 10em;
  width: 100px;
  padding: 1em;
  border: 5px solid rgb(29, 29, 116);
  border-radius: 1em;
  background: linear-gradient(#7CB9E8, #00FFFF);
}
<div class="day">1</div>
<div class="day">2</div>
<div class="day">3</div>
<div class="day">4</div>
<div class="day">5</div>
<div class="day">6</div>
<div class="day">7</div>
<div class="day">8</div>
<div class="day">9</div>
<div class="day">10</div>

Advertisement

Answer

Define a CSS class that has the style for green background color and using javascript, just toggle that class on each div element.

const days = document.getElementsByClassName('day');

for (let i = 0; i < days.length; i++) {
  days[i].addEventListener('click', function(e) {
    days[i].classList.toggle("green");
  });
}
.day {
  height: 30px;
  width: 30px;
  padding: 1em;
  border: 5px solid rgb(29, 29, 116);
  border-radius: 1em;
  background: linear-gradient(#7CB9E8, #00FFFF);
}

.green {
  background: linear-gradient(#7ce8b6, #00ff2a);
}
<div class="day">1</div>
<div class="day">2</div>
Advertisement