AllTheTime1111
AllTheTime1111

Reputation: 111

How do I reverse an onclick event with another click?

function show()
{
var elem = document.getElementById("pop").querySelector('li:nth-child(3)');
elem.style.width = "500px";
}
</script>

I have this code attached to an onclick

<li onclick="show()">

The element is originally 200px and then turns into 500px when clicked. How do I make it work so that when I click it again it goes back to 200??

Upvotes: 2

Views: 6696

Answers (3)

Felix Kling
Felix Kling

Reputation: 817238

The best thing to do would be to use a CSS class to set the width. This has the advantage that:

  • You don't have to specify the width in multiple places (CSS and JS) (-> easier to maintain)
  • You don't have to know the default width of the element (-> more flexible)

Example:

CSS:

.wide {
    width: 500px;
}

HTML:

<li onclick="show(this)">...</li>

JS:

function show(elem) {
    elem.classList.toggle('wide');
}

DEMO

Have a look at the MDN documentation regarding classList for information about browser support. You can also find alternatives in this excellent question/answer about handling CSS classes on elements: Change an element's class with JavaScript

To learn more about event handling (ways to bind event handlers, information available inside event handlers, etc), have a look at the excellent articles at quirksmode.org.

Upvotes: 3

okcoker
okcoker

Reputation: 1349

function show() {
    var elem = document.getElementById("pop").querySelector('li:nth-child(3)'),
        width = parseInt(elem.style.width, 10);
    if (width === 500) {
        elem.style.width = "200px";
    }
    else {
        elem.style.width = "500px";
    }
}

Although, I'd probably name the function toggle or something similar and not inline the click handler.

Upvotes: 1

vsgoulart
vsgoulart

Reputation: 151

Use a control variable

var clickControl = false;
function show()
{
    if(clickControl)
    {
        var elem = document.getElementById("pop").querySelector('li:nth-child(3)');
        elem.style.width = "500px";
        clickControl = !clickControl;
    }
    else
    {
        var elem = document.getElementById("pop").querySelector('li:nth-child(3)');
        elem.style.width = "200px";
        clickControl = !clickControl;
    }
}

Upvotes: 0

Related Questions