Reputation: 11
I am a bit new to jquery, I wanted to know if there is a simple way to close a div if one click out of it.
here's my HTML:
div#divlight {
background: none repeat scroll 0 0 #fff;
border: 2px solid #000000;
height: 600px;
left: 150px;
top: 10p;
padding: 15px;
position: absolute;
width: 800px;
overflow: scroll;
}
<body>
<div id="divlight">
</div>
</body>
And this is my JS
$(function(){
$('#divlight').hide();
});
$("#show").click(function()
{
$("#divlight").show();
});
$("#hide").click(function()
{
$("#divlight").hide();
});
});
Upvotes: 1
Views: 58
Reputation: 7997
I normally use focusout
for that:
$('#divlight').on('focusout', function(){
$(this).hide()
});
with the advantage of not needing to create a document click event
Upvotes: 0
Reputation: 66103
You can take advantage of .stopPropagation()
event:
$(function(){
$('#divlight').hide();
// Stop click events from bubbling up to document
$("#show").click(function(e) {
e.stopPropagation();
$("#divlight").show();
});
// Stop click events from bubbling up to document
$("#hide").click(function(e) {
e.stopPropagation();
$("#divlight").hide();
});
// Bind click event to document
$(document).click(function(e) {
$("#divlight").hide();
});
});
Upvotes: 0
Reputation: 318182
Sure is, you can listen for all clicks, and if the target element is not within #divlight
, close it
$(function(){
$('#divlight').hide();
$("#show").click(function() {
$("#divlight").show();
});
$("#hide").click(function() {
$("#divlight").hide();
});
$(document).click(function(e) {
if ( ! $(e.target).closest("#divlight").length ) {
$("#divlight").hide();
}
});
});
Upvotes: 1