Search code examples
javascriptbackgroundtoggle

Change backround color to oroginal in javascript


<div class="container">
    <div class="square extra" id="test"></div>
</div>

var color = document.getElementById('test');
function changeColor(){
color.style.background = "cornflowerblue";}

color.addEventListener('click', changeColor)

how do I reverse background color to original by pressing same div again?


Solution

  • I would create a class with the background color, then change the function to toggle the class.

    See snippet below:

    var color = document.getElementById('test');
    
    function changeColor() {
      color.classList.toggle(`bgCornflowerblue`);
    }
    
    color.addEventListener('click', changeColor)
    .square {
      background: CadetBlue;
      color:white;
      padding: 5px;
    }
    
    .bgCornflowerblue {
      background: Cornflowerblue!important
    }
    <div class="container">
      <div class="square extra" id="test">Click me</div>
    </div>