Multiple buttons for the same function with the if statement

advertisements

I've tried to make my own case function, but I cannot get it to "show stuff" once I've hidden them on first click. So my question is what am I doing wrong, how can I solve it, and how should I've done it instead?

My only requirement is that multiple buttons can use the same code to show/hide the same object – hence things like oddClick won't work since that'll require unnecessary clicks to get even/odd again (I think?).

        $('.boxbtn').on('click', function () {
        var boxwidth = $('.box').width();
        console.log(boxwidth);
        console.log('-'+boxwidth+'px');
        var state = 1;

        if(state == 0) {  // I think we are trying to compare value here.
/*              alert("foo"); */
            var state = 1;
            console.log(state);
            /*show stuff here*/
        }
        else {
/*              alert("bar"); */
            var state = 0;
            console.log(state);
            /*hide stuff here*/
        }

    });


this line 5: var state = 1; causes it to always go into "else

var state = 1; //placed on global scope
 $('.boxbtn').on('click', function () {
        var boxwidth = $('.box').width();
        console.log(boxwidth);
        console.log('-'+boxwidth+'px');
        //var state = 1; removed from function scope

        if(state == 0) {
/*              alert("foo"); */
            state = 1;
            console.log(state);
            /*show stuff here*/
        }
        else {
/*              alert("bar"); */
            state = 0;
            console.log(state);
            /*hide stuff here*/
        }

    });

Fiddle: http://jsfiddle.net/8ubk5c0f/