1

Live site- http://www.arif-khan.net/other/toggle.html

Red bar on the left side is a switch to toggle a div. My problem is when you click it for first time it doesn't work, subsequent clicks it behaves as expected. I'm pretty sure that is because first time it hide div then show div. I need to fix that, so on first click it show corresponding div instead of hide it.

Code-

<script>
var speed = 300;
        $('#close-bar').on('click', function(){                
            var $$ = $(this);

            if( $$.is('.hide-bar') ){
                $('#toggleBox').animate({left:-212}, speed);
                $$.removeClass('hide-bar')
            } else {
                $('#toggleBox').animate({left:0}, speed);
                $$.addClass('hide-bar')
            }

        });
</script>

2 Answers 2

4
var speed = 300;
$('#close-bar').on('click', function () {
    if ($(this).hasClass('hide-bar')) {
        $('#toggleBox').animate({left:0}, speed);        
        $(this).removeClass('hide-bar');
    } else {
        $('#toggleBox').animate({left:-212}, speed);
        $(this).addClass('hide-bar');
    }
});

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

Works great. Good job.
0

Could try removing the is portion and replacing with hasClass (http://api.jquery.com/hasclass/)

if($$.hasClass('hide-bar')){

}else{

}

1 Comment

Try wrapping it in a $(function(){ });

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.