When using jQuery's click()
, only one function can be specified to be called when the click event is triggered. To switch between functions, you can utilize an if statement along with the data property of the element:
$('#toggle').click(function() {
if(!$('#popout').data('open')){
$('#popout').animate({ top: '-10px' }, 'slow', function() {
$('#toggle').html('Close');
}).data('open', true);
} else {
$('#popout').animate({ top: '50px' }, 'slow', function() {
$('#toggle').html('Show');
}).data('open', false);
}
});
Remember to enclose values in quotes when specifying units for styles like top: '10px'. However, in this case, utilizing just numbers (-10 and 50) will work fine as jQuery assumes pixels by default if not specified.
Check out the code on JSFiddle
If you prefer shorter code, ternary operators can be used:
$('#toggle').click(function() {
isOpen = $('#popout').data('open');
$('#popout').animate({ top: isOpen ? '50px' : '-10px' }, 'slow', function() {
$('#toggle').html(isOpen ? 'Close' : 'Open');
}).data('open', isOpen ? false : true);
});
View the updated version on JSFiddle