I've searched and search not only google but also here and still have to find a solution that will work.
I have a div that is hidden by default, then toggled by clicking on a link. I also want it to hide when you click outside of the div. Simple, I thought, but nothing I've tried had worked yet.
This is the jquery:
<script type="text/javascript">
function toggleDiv(divID) {
$("#"+divID).fadeToggle(200);
}
</script>
And the link that toggles it:
<a onclick="toggleDiv('myDiv');">Link</a>
And then the div:
<div id="myDiv">
stuff
</div>
If anyone has any advice, I would really appreciate it.
This should do the trick for you:
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 →
EDIT: Now works for all scenarios.
You can just a add click handler on body
as a click anywhere will "bubble up" to this element.
$("body").click(function(){ $("#myDiv").fadeOut(200); });
You might also like to add a class on toggled elements in your demo code so you can target these more specifically when you want to hide them.
function toggleDiv(divID) {
$("#"+divID).fadeToggle(200).toggleClass("visible");
}
$("body").click(function(){
$(".visible").fadeOut(200, function(){
$(this).removeClass("visible");
});
});
If you don't want the visible div
to hide when clicked itself you'll also need to cancel clicks on those elements, maybe using jQuery's live()
method.
$(".visible").live("click", function(e){ e.stopPropagation(); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With