I am developing a simple dropdown menu with jQuery . When a user press on a trigger area, it will toggle the dropdown area. My question is how to have a click event outside of the dropdown menu so that it close the dropdown menu ?
I am developing a simple dropdown menu with jQuery . When a user press on a trigger area, it will toggle the dropdown area. My question is how to have a click event outside of the dropdown menu so that it close the dropdown menu ?
There is a tricky way to do this. You can manipulate blur event by adding tabIndex.
$('.click').click(function (e) {
$(this).siblings('.dropdown').fadeToggle(100);
});
$('.container').blur(function (e) {
$('.dropdown').fadeOut(100);
});
.container{
position: relative;
display: inline-block;
}
.click{
cursor: pointer;
user-select: none;
z-index: 1;
}
.dropdown{
position: absolute;
left: 0;
top: 100%;
display: none;
background: #eee;
padding: 1rem;
z-index: 2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section class="container" tabIndex="1">
<section class="click">click this</section>
<section class="dropdown">
dropdown menu here
</section>
</section>
<br /> <br />
<section class="container" tabIndex="2">
<section class="click">click this</section>
<section class="dropdown">
dropdown menu here
</section>
</section>