简体   繁体   中英

Hide div when clicking outside

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(); });
$(document).mouseup(function(e) {
                var container = $("#form1");

                if (container.has(e.target).length === 0) {
                    container.hide();
                    $('#signupSection').css('display', 'none');
                    $('#signupSection2').css('display', 'block');
                }
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM