pjk_ok
pjk_ok

Reputation: 967

How to Create A Toggle with a Var to change state in Vanilla JS

I would like to add a simple click toggle with vanilla JS, but I seem to have hit a wall. I've create a variable to change the state of the function after clicking, but it doesn't seem to work. I'm starting to pull my hair out a bit now.

There is a pen here to show the problem: https://codepen.io/emilychews/pen/dWByjx

The code is here for quick reference:

HTML

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

CSS

.box {
font-family: arial;
letter-spacing: 1px;
display: flex;
justify-content: center;
align-items: center;
height: 200px;
width: 200px;
background-color: blue;
color: white;
}

JS

var box = document.querySelectorAll('.box')[0];
var isBlue = true;

if (isBlue === true) {

  box.onclick = function() {

  box.style.background = 'red';
  isBlue = false;
  }  

} else {

  box.onclick = function() {

  box.style.background = 'blue';
  isBlue = true;
  }

}

Any help ideas would be wonderful.

Emily

Upvotes: 0

Views: 558

Answers (1)

Hugues M.
Hugues M.

Reputation: 20477

Your test if (isBlue) is evaluated only once, at the beginning, and installs the onclick listener that changes color from blue to red. From then on, that same listener will always be executed, and set the color to red.

Instead, put your if/else logic inside the function:

var box = document.querySelectorAll('.box')[0];
var isBlue = true;
box.onclick = function() {
  if (isBlue) {
    box.style.background = 'red';
    isBlue = false;
  }
  else {
    box.style.background = 'blue';
    isBlue = true;
  }
}

Upvotes: 2

Related Questions