James Deadman
James Deadman

Reputation: 301

Open/Close on click JQuery

When the ID 'Home' is clicked in the following example, the div.panel will appear, and then if the ID 'Home' is clicked again, the div.panel is hidden. Currently I have this:

$(document).ready(function() {
$('#home').on('click', function() {
    $('div.panel').animate({
        'width': 'show'
    }, 1000, function() {
        $('div.home').fadeIn(500);
    });
});

$('#home').on('click', function() {
    $('div.home').fadeOut(500, function() {
        $('div.panel').animate({
            'width': 'hide'
        }, 1000);
    });
});
});

Upvotes: 2

Views: 19072

Answers (2)

ulf_t
ulf_t

Reputation: 380

Your code is at one point redundant (the double defintion of $('#home').on('click', function()...), you need just one of them. To realise what you describe, jqueries' "toggle" is your friend. It could be done like this:

$('#home').on('click', function() {
    $('div.panel').animate({
        'width': 'toggle'
    }, 1000); });

See this Fiddle for a working example.

Upvotes: 1

Blazemonger
Blazemonger

Reputation: 92893

By duplicating the event handler as you are, both of those functions will attempt to run at the same time whenever #home is clicked. You need to use a conditional to decide whether to run one or the other.

$(document).ready(function () {
    $('#home').on('click', function () {
        if ($('div.home').is(':visible')) {
            $('div.home').fadeOut(500, function () {
                $('div.panel').animate({
                    'width': 'hide'
                }, 1000);
            });
        } else {
            $('div.panel').animate({
                'width': 'show'
            }, 1000, function () {
                $('div.home').fadeIn(500);
            });
        };
    });
});

Upvotes: 4

Related Questions