1

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".

1 Answers1

0

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

Mehdi Dehghani
  • 10,970
  • 6
  • 59
  • 64
  • stopPropagation was what I missed. Thank you so much, it's working great and I learnt something new!!! –  Aug 25 '16 at 15:50
  • Happy to help, related about `stopPropagation`: [jQuery - event.stopPropagation()](https://api.jquery.com/event.stoppropagation/) and [MDN - Event.stopPropagation()](https://developer.mozilla.org/en/docs/Web/API/Event/stopPropagation) – Mehdi Dehghani Aug 25 '16 at 15:54