<?php
// Scenario: an apply/submit/refresh button is clicked (in this case the Number Range facet's Go button)
// On click, the Proximity facet should use the first item in the dropdown if any text is entered in the input field,
// but not if the user actually made a selection (by clicking an item in the dropdown or using Enter/Return).
// This involves killing the original click event on the button first. Then detecting any selection in the Proximity.
// If there is no selection, trigger a click on the first dropdown item so it is selected, and perform the original refresh.
add_action( 'wp_head', function() {
?>
<script>
// This needs to run as early as possible, in the head
document.addEventListener('DOMContentLoaded', function() {
// First we need to kill the existing click event on the Number Range button
const selectorToIntercept = '.facetwp-type-number_range .facetwp-submit';
document.addEventListener('click', function(event) {
const clickedButton = event.target.closest(selectorToIntercept);
if (clickedButton) {
event.preventDefault();
event.stopImmediatePropagation();
const clickEvent = new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window
});
// Then, if there is text in the Proximity facet, trigger the first item,
// if the facet is not already having a selection
const proximityFacet = document.querySelector('.facetwp-type-proximity');
const firstLocation= document.querySelector('.location-result:first-child');
if( firstLocation && proximityFacet.classList.contains('not-active')) {
firstLocation.dispatchEvent(clickEvent);
}
// Then refresh again
if ('undefined' !== typeof FWP) {
FWP.refresh();
}
}
}, true);
});
</script>
<?php
}, 100 );