jquery - clicking outside of div
Right now, I just have something that slides open if hovered over, and slides closed if the mouse leaves. I'd like if I could keep it open until som开发者_开发问答eone clicks outside of it.
Ideas?
First just assign a mouseenter
event so that it opens when you hover:
$('#someDiv').mouseenter(function() {
$(this).codeToOpenIt
});
Then place a click event on the document to close it when the user clicks anywhere.
$(document).click(function() {
$('#someDiv').codeToCloseIt
});
The reason this works is that events bubble from the element that was clicked, up to the root. So placing a click()
event on the document
will catch all clicks on the page, and will close your element.
Note that any elements on the page that have a click that does:
return false;
or
event.stopPropagation();
will cause the bubbling to halt, preventing the handler on the document from firing.
精彩评论