The code snippet below fails to combine the setTimeOut and event.key functions. The serchOverlay window closes when you press any key, but should only close when you press Escape. If you remove the setTimeOut function, then the window is closed only by pressing Escape. But because of this, the animation stops working - the smooth appearance of the overlay. How to deal with the problem?
function searchClose(event) {
searchOverlay.removeAttribute('style');
setTimeout(function () {
if (event.key === 'Escape' || !event.target.closest(".search-inner")) {
body.classList.remove('is-search-open');
event.stopPropagation();
}
}, 200);
}
searchOverlay.addEventListener('keydown', searchClose);
searchOverlay.addEventListener('click', searchClose);