Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide div when clicking outside

Tags:

jquery

hide

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.

like image 595
scferg Avatar asked Dec 10 '22 07:12

scferg


2 Answers

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.

like image 78
mVChr Avatar answered Dec 29 '22 18:12

mVChr


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(); });
like image 40
Marcel Avatar answered Dec 29 '22 18:12

Marcel