Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If div is not hidden click anywhere to hide [duplicate]

I am trying to make a div hidden by default and show by clicking a button. To close the div, I can either click on the button or anywhere else on the screen. Below is my attempt but the closing part is not working. I appreciated if anyone can point me to the right implementation or maybe a better way to do this.

$('#theDiv').hide();

$("#showDivBtn").click(function(){
  $("#theDiv").show();
});

if ( !$('#theDiv:hidden') ) {

$(document).click(function() {
    $('#theDiv').hide();
});
$('#theDiv').click(function(e) {
    e.stopPropagation(); 
    return false;        
});

}

});
like image 347
Poyi Avatar asked Jun 12 '13 05:06

Poyi


People also ask

How do I hide a div on outside click?

To hide an element when clicked outside: Add a click event listener to the document object. On each click, check if the clicked element is outside of the specific element using the contains() method. If the clicked element is outside, hide the original element.

How do I show and hide a div on click?

To show and hide div on mouse click using jQuery, use the toggle() method. On mouse click, the div is visible and on again clicking the div, it hides.

How do you hide a div in 5 seconds?

Approach: Select the div element. Use delay function (setTimeOut(), delay()) to provide the delay to hide() the div element.


1 Answers

placing the entire event handler inside a condition only checks the condition on first pageload, and the event handler is probably never attached, try it like this instead :

$('#theDiv').hide();

$(document).on('click', function(e) {
    if ( $(e.target).closest('#showDivBtn').length ) {
        $("#theDiv").show();
    }else if ( ! $(e.target).closest('#theDiv').length ) {
        $('#theDiv').hide();
    }
});

FIDDLE

like image 79
adeneo Avatar answered Oct 21 '22 23:10

adeneo