Using JavaScript to track events

Hello guys,

I´ve got no luck with the event tracking so far.
Already using some scripts (Pirsch and others) on the website, but not super familiar with the whole thing – so maybe there´s a major mistake in how I approach this.

pirsch.js and pirsch-events.js are both implemented in the header.

What I´ve tried:

  1. Track click on form button. I´ve added the script recommended here to the “custom script” area of my gravity form (there are other scripts successfully running from there)
    Result: no Event tracked, no note in my browser console

  2. Because of the event listener, I was thinking – this might need to be implemented in the header of each page, not only in the form scripts.
    So I´ve removed the script from there and put it below the pirsch.js and pirsch-events.js in the header.
    Result: no Event tracked, no note in my browser console

I´ve then tried the same with the " Example 4: Tracking a Form Submission", with the same results.

I´ve made sure to use the correct selector of the (1) form button and (2) the form itself.

Tried different browsers to trigger an event too.

What am I doing wrong?
TIA

Hi Tom,

We recently consolidated all scripts, so the first thing I would recommend doing (although it’s not required) would be to replace pirsch.js and pirsch-events.js with pa.js. You can copy the new script snippet from the Integration settings page. You might want to look into disabling features though.

A good way to test your selectors is by running them from the browser console or logging them. Instead of using the entire button click tracking code, for example, you could replace it with a simple console.log.

<button id="button">Send Event</button>

<script>
    document.addEventListener("DOMContentLoaded", () => {
        console.log(document.getElementById("button"));
    });
</script>

This should log the button in the console. Or by directly running this command from the console.

document.getElementById("button")

Of course, you might need to adjust the selector.

To help you better, it would be good if I could take a look at your site. If you don’t want to share it openly here, please send an email to support@pirsch.io.

In case you haven’t seen it, we have a full web demo over here on GitHub, which might be helpful to look into.

Hi Marvin,

thanks for your help!
Yesterday I´ve tried to track the button click of a second button within a multi-page form.

Today, for testing, I´ve changed it to track the very first button → that worked.

So my insight was → it probably does not track the second button click, because the form updates with ajax, the page does not reload, so the event listener cannot attach to any elements which do not get loaded initially.

So… with the help of our chatty friend and a few rounds of debugging, this script is now working fine for

  • Gravity Forms multi page ajax loaded forms
  • desktop and mobile
  • for various form IDs used across the website
<script> 
document.addEventListener("DOMContentLoaded", () => {
    let clicks = 1;

    // General function to attach event listeners based on form ID
    function setupFormTracking(formId) {
        const buttonId = `gform_next_button_${formId}_20`; //update accordingly
        const iframeId = `gform_ajax_frame_${formId}`;
        const confirmationMessageId = `gform_confirmation_message_${formId}`;

        // Event listener for button clicks
        document.body.addEventListener("click", event => {
            if (event.target.id === buttonId) {
                pirsch("Button Clicked", {
                    duration: 42,
                    meta: {
                        Clicks: clicks
                    }
                }).then(() => {
                    clicks++;
                }).catch(e => {
                    console.error(e); // log the error but still count up
                    clicks++;
                });
            }
        });

        // Set up an observer to watch for changes in the iframe
        const iframe = document.getElementById(iframeId);
        if (iframe) {
            const checkIframeContents = () => {
                try {
                    const iframeDocument = iframe.contentDocument || iframe.contentWindow.document;
                    const targetElement = iframeDocument.getElementById(confirmationMessageId);
                    if (targetElement) {
                        pirsch("Form Submitted", {
                            duration: 42,
                            meta: {
                                TotalClicks: clicks
                            }
                        }).catch(e => {
                            console.error(e); // log the error on submission tracking failure
                        });
                    }
                } catch (error) {
                    console.error("Error accessing iframe contents:", error);
                }
            };

            // Listen for the load event which indicates content might have changed
            iframe.addEventListener('load', checkIframeContents);
        }
    }

    // Setup tracking for each form
    setupFormTracking(16); //update accordingly
    setupFormTracking(17); //update accordingly
    setupFormTracking(18); //update accordingly
});
</script>
1 Like

Awesome! :+1:

If you dynamically create elements on the page using JavaScript after the Pirsch script has already loaded, events won’t be attached. So your solution is correct, adding a listener and manually triggering the event after the form element has been created works.

1 Like