Reputation: 341
How can I hide a <div>
box when some one clicks outside of the box. I can't find the problem. So please, help me solve this problem.
<html>
<head>
<title>Test jQuery</title>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#button-upload').click(function() {
$('#id_menu_profile').show();
});
});
var $box = $('#id_menu_profile');
$(document.body).click(function(){
if (!$box.has(this).length) { // if the click was not within $box
$box.hide();
}
});
</script>
</head>
<body>
<dl>
<dt><a id="button-upload" href="#">Profile<img src="menu.png" name="arrow_profile"></a></dt>
<!-- Submenu -->
<div id="id_menu_profile" style=" display: none;">
<dt><a href="index.html">Your Id</a></dt>
<dt><a href="index.html">Account Setting</a></dt>
<dt><a href="index.html">Change Password</a></dt>
</div>
</dl>
</body>
</html>
Upvotes: 0
Views: 1854
Reputation: 50573
You just need to stopPropagation()
on the box click, so the event does not get to Document
click handler, like this:
var $box = $('#id_menu_profile');
$(document.body).click(function(){
// click outside $box
$box.hide();
});
$box.click(function(e){
e.stopPropagation(); //Don't let the box click bubble up to Document
// click within $box
});
Upvotes: 0
Reputation: 2602
This should do it:
var openDiv;
function toggleDiv(divID) {
$("#" + divID).fadeToggle(200, function() {
openDiv = $(this).is(':visible') ? divID : null;
});
}
$(document).click(function(e) {
if (!$(e.target).closest('#'+openDiv).length) {
toggleDiv(openDiv);
}
});
Example: http://jsfiddle.net/CHP5w/161/
Upvotes: 1