user1788364
user1788364

Reputation: 1151

jQuery close side menu once it has closed

I thought this would be easy but after trying lots of different things I'm stumped!

I have a slide out menu that comes out when a user clicks on a button.

There are going to be multiple slide out menus so I want to make sure that if a user clicks another button the previous menu will slide in and the new one will be revealed. I've got this working ok.

The problem I'm having is I'd like the user to be able to close the menu when they click on the button again.

E.G. The user clicks on Button 1 and the menu slides out and is revealed. The user clicks on Button 1 again and the menu will close.

I want both bits of functionality and I can only seem to get one or the other working. Any ideas where I'm going wrong?

<body>
    <div class="sidemenu button1"></div>    
    <div class="sidemenu button2"></div>

    <a class="smbtn" data-role="button1">BUTTON 1</a>
    <a class="smbtn" data-role="button2">BUTTON 2</a>
</body>

jQuery

$('.smbtn').click(function(){
    $('body').removeClass('smopen');
    $('.sidemenu').removeClass('open');
    $('.smbtn').removeClass('active');  

    var datarole = $(this).attr('data-role');       
    if (!$(this).hasClass("active")) {
        $(this).addClass('active');
        $('body').addClass('smopen');
        $('.sidemenu.'+datarole).addClass('open');
    }
});

You can see the fiddle here: http://jsfiddle.net/z5X2E/

Upvotes: 0

Views: 296

Answers (2)

webdeveloper
webdeveloper

Reputation: 17288

More elegant solution:

var $body = $('body'),
    $sidemenu = $('.sidemenu');

$('.smbtn').click(function()
{
    var $btn = $(this);
    $sidemenu.removeClass('open');
    $btn.toggleClass('active').siblings('.smbtn').removeClass('active');

    if($btn.hasClass('active'))
    {
        $body.addClass('smopen');
        $sidemenu.filter('.' + $btn.data('role')).addClass('open');
    }
    else $body.removeClass('smopen');
});

Demo: http://jsfiddle.net/z5X2E/1/

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Try

$('.smbtn').click(function () {
    $('.sidemenu.open').removeClass('open');

    var datarole = $(this).attr('data-role');
    if ($(this).hasClass("active")) {
        $(this).removeClass("active");
        $('body').removeClass('smopen');
    } else {
        $('.smbtn.active').removeClass('active');
        $(this).addClass('active');
        $('body').addClass('smopen');
        $('.sidemenu.' + datarole).addClass('open');
    }
});

Demo: Fiddle

Upvotes: 3

Related Questions