Search code examples
jqueryhtmlclickfade

Click div, fade in div, click div OR outside div to fade out div


So I have a little code, that I know works, that makes it so when you press on a div it opens a second div (which is set to display: none in css). You then click on the same div that you click to open the second div to close it (fade out).

However, I want to be able to make it so you can click OUTSIDE and it would fade out. I've tried numerous of codes, yet I cannot get it working. Please help!

$(document).ready(function() {
    $("#dashbox").click(function() {
        $("#dashboardbox").fadeToggle();
    });
});

Solution

  • Add a click event to the document that, if the box is not already invisible, checks that it did not get triggered by clicking #dashboardbox or #dashbox (would trigger toggle twice) or any of their children. If all is well it will then fade out the box.

    $(document).ready(function() {
        $(document).click(function(e) {
            // Skip if already hidden
            if(!$('#dashboardbox').is(":visible"))
                return;
    
            // Skip if clicked dashbox or its children
            if ($(event.target).closest('#dashbox').length)
                return;
    
            // Skip if clicked dashboardbox or its children
            if ($(event.target).closest('#dashboardbox').length)
                return;
    
            // Fade out
            $("#dashboardbox").fadeOut();
        });
    
        $("#dashbox").click(function(e) {
            $("#dashboardbox").fadeToggle();
        });
    });
    

    Fiddle here.