document.addEventListener('DOMContentLoaded', function () {
// Function to update the facet input field based on the URL
function updateFacetFromUrl() {
const facetInput = document.querySelector('#wpgb-facet-2'); // The facet search input field
// Ensure the facet input exists
if (!facetInput) {
console.error('Facet input field not found!');
return;
}
const urlParams = new URLSearchParams(window.location.search);
const facetValue = urlParams.get('_search_facet'); // Get the _search_facet parameter from the URL
console.log('Facet value from URL:', facetValue); // Log the URL parameter
// Check if the facet value from the URL is different from the current value
if (facetValue !== null && facetValue !== facetInput.value) {
console.log('Updating facet input value to:', facetValue); // Log the value that will be set
facetInput.value = facetValue; // Set the value of the input field to the URL's facet value
// Optionally, trigger any grid update or refresh logic if needed here
}
}
// MutationObserver to check if the facet input is added dynamically
const observer = new MutationObserver(function (mutationsList, observer) {
// Check if the facet element is added to the DOM
const facetInput = document.querySelector('#wpgb-facet-2');
if (facetInput) {
// Stop observing once the facet input is found
observer.disconnect();
updateFacetFromUrl(); // Update the facet value based on the URL
}
});
// Start observing the DOM for changes
observer.observe(document.body, { childList: true, subtree: true });
// Listen for changes in the URL (back/forward navigation)
window.addEventListener('popstate', function () {
updateFacetFromUrl(); // Update the facet input when navigating using back/forward buttons
});
// Watch the URL periodically for changes (you can adjust the interval)
setInterval(function () {
updateFacetFromUrl(); // Update the facet every 500ms to keep it in sync with the URL
}, 500); // Check every 500 milliseconds (adjust if necessary)
// Update the facet input when the page loads
updateFacetFromUrl();
});