I have a button #clickme. When clicked a div #cart slides up, when clicked again it slides down.
I also want to be able to close it by clicking anywhere else on the page apart from #cart or #clickme.
The code I’ve attempted doesn’t quite work. What happens now is that when I click #clickme, it slides up and then back down again quickly.
I imagine what is happening is that the click event is triggered at both the document and #clickme levels, causing one effect after the other.
What’s an elegant way around this?
$('#clickme').click(function() {
if ($("#cart").is(":hidden")) {
$("#cart").slideDown("slow");
} else {
$("#cart").slideUp("slow");
}
});
$(document.body).click(function () {
if ($("#cart").not(":hidden")) {
$("#cart").slideUp("slow");
}
});
As jAndy states the problem is event bubbling here, but you since you asked “is there a more elegant way”, yes there is 🙂
If we take advantage of
.slideToggle()and the:visibleselector, your code comes very terse indeed, you can do this:.slideToggle()does almost exactly the check you’re doing, The difference is it checks when it gets there, so in the case of queued animations it’s even better. And by using:visiblewe’re only selecting#cartif it’s visible and needs sliding up, otherwise there’s nothing selected. The.stop()call is just to prevent animation queue-up for fast clicks, test it out and see what behavior you want, this part is optional.And last the
event.stopPropagation()call is to prevent the click event from bubbling up to document and triggering it’s.click()handler, (click here for more info on that).