Matthieu Boisjoli Matthieu Boisjoli - 1 year ago 56
HTML Question

How to close a div by clicking outside of it

I made a search for one of my websites and when I press on my div, it shows all the categories. When you click on a category, then the div close by itself. My issue here is if the customer click on my div and doesn't want to click on any category, I want this div to be closed whenever this customer is clicking anywhere outside of it.

Here's my HTML :

<div id="wrap-categories">
<p>Choose a category</p>
<img src="..." alt="white-arrow">
<ul class="" style="display: none;">

<li data-value="1">Category 1</li>
<li data-value="2">Category 2</li>
<li data-value="3">Category 3</li>

</ul>
</div>


And this is my Javascript, which is not working properly whenever I try to click outside of the div to close it :

$('#wrap-categories > p').click(function() {
$('#wrap-categories > ul').addClass('opened').show();
});

if($('#wrap-categories > ul').hasClass('opened')) {
$(document).click(function(e) {
console.log(1);
// close div here
});
}


What it does is even when I click on the div #wrap-categories, it already put a 1 in console.log. But I really need to close it only when the user is cliking outside of it when the div is opened, and also has the class "opened".

Answer Source

Did you mean this?

$('#wrap-categories').click(function(e) {
    e.stopPropagation();
});
$('#wrap-categories').click(function() {        
    $('#wrap-categories > ul').addClass('opened').show();
});

$(document).click(function() {      
    $('#wrap-categories > ul').removeClass('opened').hide();
});

jsfiddle