The dropdown menu should open when the button is clicked.
And if you click outside the dropdown it should close again.
I tried this by adding an event listener to the body when the dropdown menu is active and then checking if the click happened outside the dropdown.
How can I write the following code without timeout function and make the dropdown close when clicked outside and not inside?
<div class="dropdown dropdown__open">
Open Dropdown
<div class="dropdown__window">
<a class="dropdown__link">Link Text</a>
<a class="dropdown__link">Link Text</a>
<a class="dropdown__link">Link Text</a>
<a class="dropdown__link">Link Text</a>
</div>
</div>
.dropdown {
position: relative;
cursor: pointer;
user-select: none;
&__window {
position: absolute;
background: $background-alt;
width: 100%;
max-width: 260px;
top: 45px;
z-index: 12;
overflow: hidden;
display: none;
visibility: hidden;
&--active {
display: block;
visibility: visible;
}
> * {
width: 100%;
display: block;
color: $white;
white-space: nowrap;
&:hover {
background: $background;
color: currentColor;
}
}
}
}
let dropdownBtn = document.querySelectorAll('.dropdown__open')
dropdownBtn.forEach((el) => {
let dropdownWindow = el.querySelector('.dropdown__window')
el.addEventListener('click', function () {
dropdownWindow.classList.toggle('dropdown__window--active')
window.setTimeout(function () {
if (dropdownWindow.classList.contains('dropdown__window--active')) {
let clickListener = document.body.addEventListener(
'click',
function (event) {
if (event.target.classList != 'dropdown__link') {
dropdownWindow.classList.remove('dropdown__window--active')
// Buggy clickListener.removeEventListener()
}
}
)
}
}, 1000)
})
})