JS fix for Elementor not closing popups on anchor link click

This is a workaround for an annoying Elementor behavior…

If you embed a WordPress Menu widget in a Popup and that menu contains anchor links, the popup won’t natively close when an anchor link is clicked (and you’re on the same page as the target element).

For example, if my menu item “About” is linked to #about, clicking that menu item will scroll to the right spot, but the popup will stay open. This is a known issue.

Dropping this into the Custom Code section (and configuring it to load on whatever pages you need) will resolve this annoyance.

<script>
/* shim to allow anchor link clicks to trigger a scroll-to-element and close the parent popup */
jQuery(window).on('elementor/frontend/init', function() {
jQuery('body').on('click', '.elementor-location-popup .menu-item a', function(e) {
const currentUrl = window.location.href.split('#')[0];
const clickedUrl = this.href.split('#')[0];
// If we're on the same page
if (currentUrl === clickedUrl) {
e.preventDefault();
const hash = this.href.split('#')[1];
if (hash) {
const element = document.getElementById(hash);
if (element) {
element.scrollIntoView({ behavior: 'smooth' });
}
}
}
const popup = jQuery(this).closest('.elementor-popup-modal');
if (popup.length) {
const popupId = popup.attr('data-elementor-id');
const popupInstance = elementorFrontend.documentsManager.documents[popupId];
if (popupInstance) {
popupInstance.getModal().hide();
} else {
try {
const elementorPopup = elementorFrontend.documentsManager.documents[popupId];
jQuery(popup).find('.dialog-close-button').trigger('click');
} catch(e) {
console.error('Error:', e);
}
}
} else {
console.log('popup.length is 0');
console.log('Parent elements:', jQuery(this).parents().map(function() {
return this.className;
}).get());
}
});
});
</script>
view raw fix.html hosted with ❤ by GitHub

Leave a Comment