Basically trying to remove/toggle the 'active' class from the div, but if I click inside the children of 'parent-div' the function happens as well, and it should only work on the parent-div. It's a fixed background that should act as "click outside to close" function, and I can't disable clicking inside the children because there is a form inside in them.
Tried event.stopPropagation as well but that didn't do anything.
HTML
<div >
<div >
<div class=ims-search-input">
<form>
</form>
</div>
</div>
</div>
$(".ims-search").click(function(event){
if (!$(event.target).is('.ims-search .active')){
$(this).removeClass('active');
}
});
CodePudding user response:
You can compare event.target === event.currentTarget to see if the element clicked is the one the event is assigned to.
Events bubble up: .target will match the actually clicked element, while .currentTarget will match the selector / element the event is assigned to.
Giving:
$(".parent-div").click(function(event) {
if (event.target === event.currentTarget)
$(this).hide();
});
.parent-div { height:150px; width:150px; border:1px solid blue; position:relative; }
#inner { left:50px;top:50px;height:50px;width:50px; background-color: pink; position:relative; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<div id="inner">
don't click here
</div>
</div>
