Synchronize user input to HTML form elements with URL query parameters using Alpine.js.
Please take a look at the demonstration page.
To avoid making too many calls to Location or History APIs within a short timeframe extend event listener with a debounce function:
let lastChangeTime = 0;
let debounceTimeout = null;
const updateQueryParamWithConditionalDebounce = (paramName, value) => {
const now = Date.now();
const timeSinceLastChange = now - lastChangeTime;
if (timeSinceLastChange < 300) {
// If last change was recent, debounce
// to avoid making too many calls to Location or History APIs within a short timeframe
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(() => {
updateQueryParam(paramName, value);
lastChangeTime = Date.now();
}, 300);
} else {
// Otherwise, update immediately
updateQueryParam(paramName, value);
lastChangeTime = now;
}
};
// call updateQueryParamWithConditionalDebounce instead in Alpine.bind function