user1578456
user1578456

Reputation:

Issue with using one button to open/close in JQuery

Hey guys I am trying to make a button that will open and close based on if it is clicked the first time - it opens, if the second time - it closes and resets.

Here is my code I have so far - it only opens and wont close:

var val;
$(".confirmed").click(function(){
    if (val == 1){
        hide(); 
    }
    val = 1;
    $(".confirmedtable").show();
    $(".searchconfirmed").show();
});

function hide(){

            $(".confirmedtable").hide();
            $(".searchconfirmed").hide();
            val = 0;

}

Thanks

Upvotes: 0

Views: 300

Answers (3)

David Thomas
David Thomas

Reputation: 253308

As an alternative to the toggle() based answers:

$('.confirmed').click(function(){
    $('.confirmedtable, .searchconfirmed')[$('.confirmedtable').is(':visible') ? 'hide' : 'show']();
});

JS Fiddle demo.

It is, though, at best merely an alternative; the toggle() approach is more concise.

Upvotes: 1

adeneo
adeneo

Reputation: 318182

$(".confirmed").click(function(){
    $(".confirmedtable, .searchconfirmed").toggle();
});

FIDDLE

Upvotes: 1

Julio
Julio

Reputation: 2290

You can just use the toggle() function in jquery to do this. See: http://api.jquery.com/toggle/

$('#button').click(function() {
    $('#div_to_show_hide').toggle('slow', function() {
        // Animation complete.
    });
});

The toggle will show an element if it's currently hidden, and hide an element if it's currently shown.

Upvotes: 2

Related Questions