0

It's very simple thing.
I want to change a box color by one button.
What is problem in this 'if' function?

<body>
    <div class="box" style="width: 50px; height: 50px; background: brown;"></div>
    <button class="btn" value="brown">Color Change</button>
</body>

<script>
    btn = document.querySelector('.btn');
    box = document.querySelector('.box');

    btn.addEventListener('click', () => {
        if (box.style.backgroundColor = 'brown'){
            box.style.backgroundColor = 'black';            
        } else{
            box.style.backgroundColor = 'brown';
        }
    })
</script>

1 Answers1

-1

Check this:

  btn = document.querySelector('.btn');
    box = document.querySelector('.box');

    btn.addEventListener('click', () => {
        if (box.style.backgroundColor == 'brown'){
            box.style.backgroundColor = 'black';            
        } else{
            box.style.backgroundColor = 'brown';
        }
    })
  <div class="box" style="width: 50px; height: 50px; background: brown;"></div>
   <button class="btn" value="brown">Color Change</button>