0

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!

Fuego DeBassi
  • 2,967
  • 6
  • 29
  • 37

2 Answers2

3

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>
Jordan Running
  • 102,619
  • 17
  • 182
  • 182
  • This is great. Thank you! Follow up: is there a way to do it without just toggling a CSS class? Ideally I'd prefer to be adjusting the height of the element in JS (so I could apply an animation to it down the road). – Fuego DeBassi Dec 08 '15 at 00:17
2

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>
Sampson
  • 265,109
  • 74
  • 539
  • 565