Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

troccoli's avatar

Livewire methods And GA4

I have already setup Google Analytics for my project, and it tracks the pages just fine.

One of my page is a Livewire components to show some records. We only show the first 12 with a Load More button to show the next 12. This button just runs a method on the Livewire component.

I would like to track when a user clicks on the Load More button. Is there a way to achieve that?

0 likes
2 replies
LaryAI's avatar
Level 58

To track the "Load More" button clicks in a Livewire component using Google Analytics, you can use JavaScript to send an event to Google Analytics when the button is clicked. Here's a step-by-step solution:

  1. Add an Event Listener to the Button:

    First, ensure that your "Load More" button has a unique identifier or class. Then, you can use JavaScript to listen for clicks on this button.

  2. Send an Event to Google Analytics:

    Use the gtag function to send an event to Google Analytics when the button is clicked.

Here's an example of how you can implement this:

<!-- Assuming your Load More button has an ID of 'load-more-button' -->
<button id="load-more-button" wire:click="loadMore">Load More</button>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        var loadMoreButton = document.getElementById('load-more-button');

        if (loadMoreButton) {
            loadMoreButton.addEventListener('click', function () {
                // Send event to Google Analytics
                gtag('event', 'click', {
                    'event_category': 'Button',
                    'event_label': 'Load More',
                    'value': 1
                });
            });
        }
    });
</script>

Explanation:

  • document.addEventListener('DOMContentLoaded', function () {...});: This ensures that the script runs after the DOM is fully loaded.

  • loadMoreButton.addEventListener('click', function () {...});: This adds a click event listener to the "Load More" button.

  • gtag('event', 'click', {...});: This is the Google Analytics function to send an event. You can customize the event_category, event_label, and value as needed for your analytics.

Make sure that the Google Analytics script is properly included in your project and that the gtag function is available globally. This solution assumes you are using the Global Site Tag (gtag.js) for Google Analytics. Adjust the event parameters to fit your tracking needs.

troccoli's avatar

Although @laryai solution would probably work, I was looking for something to do in the Livewire component, rather than in its view.

Please or to participate in this conversation.