putyourlightson / craft-sprig

A reactive Twig component framework for Craft CMS.
https://putyourlightson.com/plugins/sprig
MIT License
129 stars 9 forks source link

Sprig Filters with Google Analytics #389

Closed AdamChlan closed 2 months ago

AdamChlan commented 2 months ago

Hello, I was curious if there is anything special we may need to be aware of when trying to track clicks on entry filters built with Sprig. We've tried a couple methods: an onclick event with a gtag; and then using GTM to track and process the click. using the Google Analytics debug console, it seems like everything is registering as expected, but the data never makes it GA4. Without getting into the actual code we are using, I was curious if there is a critical step we should be considering for this.

Plugin Version

2.8.1

bencroker commented 2 months ago

My guess is that using JavaScript listeners and triggering events programmatically should just work. All of the following result in the alert being shown.

{# Using Sprig attributes #}
<button sprig s-on:click="alert('clicked')">Filter</button>
{# Using Vanilla JS #}
<button sprig onclick="alert('clicked')">Filter</button>
{# Using the htmx Javascript API #}
<button sprig id="filter">Filter</button>
<script>
    htmx.on('#filter', 'click', () => alert('clicked'));
</script>

{# Using Vanilla JS #}
<button sprig id="filter">Filter</button>
<script>
    document.getElementById('filter').addEventListener('click', () => alert('clicked'));
</script>