landed
landed

Reputation: 478

Toggle function in javascript

I'm trying to write a simple button control in javascript that will self encpsulate toggle functionality so every time it works it changes the show or hide of an element. I thought this could be easy but I'm not able to get it to work.

simplify: function(){
    aRemoveButtons[t].show();

    //next time 
    aRemoveButtons[t].hide();
}

I tried to set a variable and then do a !variable on it but I couldn't check for its existance as it was a boolean and false was seen to be the same as undefined.

Upvotes: 1

Views: 1005

Answers (3)

Saket Patel
Saket Patel

Reputation: 6683

Ext.override(Ext.Element, {
    toggle : function()
    {
        // check current state of visibility
        var mode = this.getVisibilityMode();
        var hideClass = '';

        switch (mode) {
            case Ext.Element.prototype.VISIBILITY:
                    hideClass = 'x-hidden-visibility';
                break;
            case Ext.Element.prototype.DISPLAY:
                    hideClass = ''x-hidden-display';
                break;
            case Ext.Element.prototype.OFFSETS:
                    hideClass = 'x-hidden-offsets';
                break;
        }

        // default should be visible
        var visible = true;
            // if class exists then the element is hidden
        if(this.hasCls(hideClass)) {
            visible = false;
        }

        this.setVisible(!visible);
    }
});

Upvotes: 0

Manse
Manse

Reputation: 38147

Try something like :

function toggle(elementID) {
    var target1 = document.getElementById(elementID); // get the element
    if (target1.style.display == 'none') { // check current state
        target1.style.display = 'block'; // show
    } else {
        target1.style.display = 'none';  // hide
    }
}​

usage :

<div id="something" style="display:none;"></div>

toggle('something');

Upvotes: 0

peterp
peterp

Reputation: 3121

Are you using jQuery? It has a built-in toggle-Method: http://api.jquery.com/toggle/

$('.target').toggle();

Upvotes: 1

Related Questions