0

I'm using the following code to show the sidebar when .sidebar-toggle is pressed, and hide the sidebar when #page is pressed.

Showing the sidebar works perfect, but it doesn't hide when #page is being pressed. It looks like the variable isn't set to 1 when the .sidebar-toggle has been clicked.

var state = 0;

if (state === 0) {
    $('.sidebar-toggle').click(function() {
        $('#page').animate({marginLeft: '230px'}, 400);
        state = 1;
    });
}

if (state === 1) {
    $('#sidebar').click(function() {
        $('#page').animate({marginLeft: '0'}, 400);
        state = 0;
    });
}
2
  • It would trigger on .sidebar-toggle click, not #page click--right? Can you include your relevant HTML? Commented Apr 20, 2013 at 14:39
  • the code just runs once. so the state === 1 will never be executed... Commented Apr 20, 2013 at 14:40

2 Answers 2

1

You were forgetting to use the #page click.function ... and the best way is to put the if inside the click.function ... Try this way

var state = 0;

$('.sidebar-toggle').click(function() {
    if (state===0) {    
        $('#page').animate({marginLeft: '230px'}, 400);
        state = 1;
    }    
});

$('#page').click(function() {
    if (state===1){
        $('#page').animate({marginLeft: '0'}, 400);
        state = 0;
    }
});
Sign up to request clarification or add additional context in comments.

Comments

0

May be because this never executed

if (state === 1) {
    $('#sidebar').click(function() {
        $('#page').animate({marginLeft: '0'}, 400);
        state = 0;
    });
}

Try this way -

var state = 0;
    $('.sidebar-toggle').click(function() {
       if (state === 0) {
        $('#page').animate({marginLeft: '230px'}, 400);
        state = 1;
       }
    });

    $('#page').click(function() {
       if (state === 1) {
        $('#page').animate({marginLeft: '0'}, 400);
        state = 0;
       }
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.