Custom event listener for collection page color swatch removed after filters/sort applied

Topic summary

Problem: After adding a color swatch picker (via a tutorial) to product cards, swatch clicks correctly update images and link to the selected variant on collection/featured/search pages—until a sort or filter is applied on the collection page.

Observed behavior: Post sort/filter, swatch pills still respond to clicks but no longer update the main product image; navigation remains tied to the first image/variant. DevTools shows the custom event listeners are removed when sorting/filtering re-renders the product grid.

Implementation details:

  • Theme: Craft (likely applicable to other free themes).
  • Custom JS: card-product-variant-selection-custom.js.
  • Injected on: main-collection-product-grid.liquid.

Requested help: How to re-trigger or re-initialize the JS that attaches the event listeners after the collection grid updates due to sorting/filtering (i.e., where to hook into filter/sort change or section re-render).

Status: No solution yet; user seeks guidance on the correct hook or location to reattach listeners.

Summarized with AI on December 13. AI used: gpt-5.

I’m using Craft theme, but this is probably generic to all free themes.

I have set up my product color variants and I added a color swatch picker to the collections page, featured page and search page, as per the tutorial from Websense Pro (https://www.youtube.com/watch?v=VnVu2nhnBMU).

It all works great when I browse these page, with the clicking of each of the color circles changing the image of the product, and then clicking on that main image will take you to the product page of exactly the variant selected.

HOWEVER, when on the collections page, when applying either the sort order or filter, all works on sort and filter, but the color picker only works to click on each color pill, and does not change the main relevant image (so stays on the first image and will nav to the product of the first image).

I can see in dev tools that the event that the custom code adds as a listener to the collection products gets removed when the sort and filter is applied, so I need a way to trigger the JS that’s adding the event listener back on.

The event listener is in card-product-variant-selection-custom.js and is added on the main-collection-product-grid.liquid. So my thinking is that I need to trigger the code again on change of filter or sort, but I don’t know where to add it.

Any help would be greatly appreciated as this is driving me crazy! Thanks!