Fuego DeBassi
Fuego DeBassi

Reputation: 3017

Cycle between on/off states in javascript

Lets say I want a button to double in height when I click it, and then on the next click return to normal. So basically there is a onstate and an offstate and clicking this button just flips between them.

var button = document.getElementById("box1");
button.onclick = function() {
  ON: document.getElementById("box1").style.height = "200px";
  OFF: document.getElementById("box1").style.height = "100px";
}

How could I rewrite the function so that it keeps track of state? Any help is greatly appreciated!

Upvotes: 0

Views: 132

Answers (2)

Jordan Running
Jordan Running

Reputation: 106077

In your CSS:

#box1 {
  height: 100px;
}

#box1.on {
  height: 200px;
}

In your JavaScript:

var button = document.getElementById("box1");

button.addEventListener('click', function() {
  button.classList.toggle('on');
});

var button = document.getElementById("box1");
    
button.addEventListener('click', function() {
    button.classList.toggle('on');
});
#box1 {
  height: 100px;
}
    
#box1.on {
  height: 200px;
}
<button id="box1">Click me</button>

Upvotes: 3

Sampson
Sampson

Reputation: 268424

Add your new sizing to an .enlarge class:

button.addEventListener( "click", function () {
    button.classList.toggle( "enlarge" );
});

The classList member is supported only in IE 10 and up, but you can shim it easily.

var button = document.querySelector( "button" );

button.addEventListener( "click", function () {
   button.classList.toggle( "enlarge" );
});
.enlarge {
  font-size: 200%;
}
<button>Enlarge Me</button>

Upvotes: 2

Related Questions