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 :
Choose a category
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
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();
});
No comments:
Post a Comment