Sergio Vento
Sergio Vento

Reputation: 53

How can I reverse the function in javascript at the second click?

I need that on the second click the function come back to the original height and width Now the code is this:

<script>
function myBurger() {
    document.getElementById("burger").style.height = "200px";
    document.getElementById("burger").style.width = "300px";

    }
</script>

The website where I loaded the landing page (test) is this: http://figmentasergio.altervista.org/

Upvotes: 0

Views: 734

Answers (3)

Josh Burgess
Josh Burgess

Reputation: 9577

You could use a global variable as a state indicator, like so:

JavaScript

var isExpanded = false;

function myBurger() {
    document.getElementById("burger").style.height = isExpanded ? "10px" : "200px";
    document.getElementById("burger").style.width = isExpanded ? "10px" : "300px";
    isExpanded = !isExpanded;
}

JSFiddle Link demonstrating this, here.

I changed a few variables (and the method that it's called) via the JSFiddle, but it's the exact same concept.

The line isExpanded = !isExpanded is a bit flip, where we set the isExpanded token to its inverse.

Upvotes: 0

dfsq
dfsq

Reputation: 193301

It's more convenient to toggle CSS class:

function myBurger() {
    document.getElementById("burger").classList.toggle('expand');
}

Where

#burder.expand {
    height: 200px;
    width: 300px;
}

classList is supported in IE10+. For older browsers you can use shims or go with simple className approach.

Upvotes: 1

Code Whisperer
Code Whisperer

Reputation: 1041

Create a new function and bind it to double click since the click event is already taken. The second function should revert any action the first function did.

Upvotes: 0

Related Questions