Fix problem showing dropdown after window resize

When the browser window is resized, a new click event listener is added
to the window but the old one is not removed. The old one ends up
preventing the newly-made dropdown from opening.

Fix this by remembering the click event listener function added to the
window, and remove it before making the new dropdown after a window
resize.
This commit is contained in:
Rob Leslie 2023-04-04 15:46:04 -07:00 committed by Sodbileg Gansukh
parent b56bec2cb8
commit afca9cb27e

View File

@ -16,6 +16,7 @@
}); });
} }
var windowClickListener;
const makeDropdown = function () { const makeDropdown = function () {
if (mediaQuery.matches) return; if (mediaQuery.matches) return;
const submenuItems = []; const submenuItems = [];
@ -62,11 +63,12 @@
document.body.classList.toggle('is-dropdown-open'); document.body.classList.toggle('is-dropdown-open');
}); });
window.addEventListener('click', function (e) { windowClickListener = function (e) {
if (!toggle.contains(e.target) && document.body.classList.contains('is-dropdown-open')) { if (!toggle.contains(e.target) && document.body.classList.contains('is-dropdown-open')) {
document.body.classList.remove('is-dropdown-open'); document.body.classList.remove('is-dropdown-open');
} }
}); };
window.addEventListener('click', windowClickListener);
} }
imagesLoaded(head, function () { imagesLoaded(head, function () {
@ -75,6 +77,7 @@
window.addEventListener('resize', function () { window.addEventListener('resize', function () {
setTimeout(function () { setTimeout(function () {
window.removeEventListener('click', windowClickListener);
nav.innerHTML = navHTML; nav.innerHTML = navHTML;
makeDropdown(); makeDropdown();
}, 1); }, 1);