tags:

views:

11

answers:

1

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 someone clicks outside of it.

Ideas?

+1  A: 

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.

patrick dw
I'd add that you may not want to close the div if someone clicks inside that div, which the code above will do. To prevent this, add a click handler to the div itself that stops propagation (`event.stopPropagation()`) so that the document's click handler won't be reached.
JacobM
Also, if the element has focus, and you want you can add keystroke events - like make it close if someone hits ESC key for instance.
Mark Schultheiss