ThomasCS
ThomasCS

Reputation: 717

jquery close toggle

I have multiple buttons toggling the same div (actually iframe on my page). I want them to 'retoggle' when I click different buttons, but when I click the samen button again, I just want to close the div.

JSFIDDLE

$(document).ready(function(){
    $('.leftbutton').click(function(){
        if($('#left').is(':visible')) return ; // ignoring
        $('#right').hide();
        $('#left').fadeIn();
    });
});

$(document).ready(function(){
    $('.rightbutton').click(function(){
        if($('#right').is(':visible')){
            $('#right').fadeOut();
            $('#right').fadeIn();
        } 
        else{
            $('#left').hide();
            $('#right').fadeIn();
        }
    });
});

Upvotes: 0

Views: 443

Answers (3)

ThomasCS
ThomasCS

Reputation: 717

Both answers were usefull, and combined it gave me all the functionality I wanted.

Check out this jsfiddle: http://jsfiddle.net/thomascs/nV5Tu/

$(document).ready(function(){
    $('.leftbutton').click(function(){
        if($('#left').is(':visible')) {
            $('#left').hide();
        }
        else {
        $('#right').hide();
        $('#left').fadeIn();
        }
    });
});

$(document).ready(function(){
    $('.rightbutton').click(function() {
        if ($('#right').is(':visible')) {
              $('#right').fadeOut();
            if ($("#right").data('lastClicked') !== this) {
               $('#right').fadeIn();
            }
        } 
        else {
            $('#left').hide();
            $('#right').fadeIn();
        }
        $("#right").data('lastClicked', this);
    });
});

Thanks for your help!

Upvotes: 0

John Koerner
John Koerner

Reputation: 38087

To close the left upon clicking again, you can simply hide it instead of returning in your function. This same concept can be applied to the right buttons:

$('.leftbutton').click(function(){
    if($('#left').is(':visible'))
    {
        $("#left").hide("slide");;
        return;
    }
    $('#right').hide();
    $('#left').fadeIn();
});

http://jsfiddle.net/CfGYG/11/

Upvotes: 1

Explosion Pills
Explosion Pills

Reputation: 191809

What you can do is store the last button that was clicked as part of the target element. For example:

$(".rightbutton").on('click', function () {
   $("#right").data('lastClicked', this);

Then, compare the last clicked data with this to see whether the button should be shown or not.

http://jsfiddle.net/CfGYG/10/

Upvotes: 1

Related Questions