<?php
// Fixes closing issues with Avada theme modals that are triggered from inside a listing template:
// Avada moves modals to <body> on page load;
// After a FacetWP refresh (e.g. using facets) the new modal copies stay in the template,
// so the data-target selector now matches two modals, both open, and the extra backdrop can’t be closed.
add_action( 'facetwp_scripts', function() {
?>
<script>
// Before the refresh: remove listing modals that were moved to <body> earlier
document.addEventListener('facetwp-refresh', function() {
if ( ! FWP.loaded ) return; // skip initial page load, Avada handles that
document.querySelectorAll('.facetwp-template [data-toggle="modal"][data-target]').forEach(function(link) {
document.querySelectorAll(link.getAttribute('data-target')).forEach(function(modal) {
if ( ! modal.closest('.facetwp-template') ) {
modal.remove();
}
});
});
});
// After the refresh: move the new listing modals to <body>, like Avada does on page load
document.addEventListener('facetwp-loaded', function() {
document.querySelectorAll('.facetwp-template .fusion-modal').forEach(function(modal) {
document.body.appendChild(modal);
});
});
</script>
<?php
}, 100 );