Skip to content

Instantly share code, notes, and snippets.

@matthew-ia
Last active June 23, 2023 17:29
Show Gist options
  • Save matthew-ia/06860092d1e6340fb0b0320b526c4080 to your computer and use it in GitHub Desktop.
Save matthew-ia/06860092d1e6340fb0b0320b526c4080 to your computer and use it in GitHub Desktop.
Synthetically Click Filters Buttons (Hijack Filter Button Functionality)
/*
Synthetically Click Filters Buttons
For this snippet, some definitions:
- Filter Button – a particular filter button element that exists with the main Filter Panel
– Fit Button – a button below the fit banner, that when clicked, applies the corresponding fit's filter
Using synthetic clicks of the filter buttons within the Filter Panel, to modify the current filter state.
The standard filter buttons use the data-href attribute which is parsed and passed to an Ajax call to update the
product grid and the UI state within the Filter Panel. We're hijacking that functionality here with a bit of hack.
1. We use a string that includes the filter state we want applied to be applied,
such as Classic or Tailored (exclusively)
2. We get the element that is the filter button within the Filter Panel.
3. We update the data-href attribute value to include the string that has the filter state we want
4. We synthetically click the filter button within the Filter Panel. After this fires,
the page updates to show the correct filter state, and the filter button we manipulated is "reset"
to an appropriate UI state based on the Ajax call.
5. We use the syntheteic click functions when clicking the Filter Buttons. We would need to apply this same
thing to the corresponding mobile images as well, so on click they trigger the same functionality, the
snippet only shows an example for the fit buttons themselves.
*/
function filterClassic() {
let filterString = '/search-ajax?cgid=men-tops-polos&prefn1=fit&prefv1=Classic%20Fit'; // 1
let filter = document.querySelector('[data-id="fit-Classic Fit"] button'); // 2
filter.setAttribute("data-href", filterString); // 3
filter.click(); // 4
}
function filterTailored() {
let filterString = '/search-ajax?cgid=men-tops-polos&prefn1=fit&prefv1=Tailored%20Fit'; // 1
let filter = document.querySelector('[data-id="fit-Tailored Fit"] button'); // 2
filter.setAttribute("data-href", filterString); // 3
filter.click(); // 4
}
// 5
const classicFitButton = document.querySelector('fit-selection-buttons classic');
const tailoredFitButton = document.querySelector('fit-selection-buttons tailored');
classicFitButton.addEventListener('click', (e) => {
// Run our hack
filterClassic();
// ... Do other stuff as needed, like updating Fit button state
});
tailoredFitButton.addEventListener('click', (e) => {
// Run our hack
filterTailored();
// ... Do other stuff as needed, like updating Fit button state
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment