Skip to content

Tracking custom events

Learn how to track custom events on your website.

Custom events allow you to track specific actions or interactions on your website. This can be anything from button clicks to form submissions.

A custom event represents a specific action or interaction on your website. For example, a button click or a form submission. This can be useful to track events to measure how well your website is performing (for example, how many people sign-up while visiting your website) and to understand user behavior.

There are two ways to track custom events:

  1. Using the SDK - Import and call trackEvent() from the @lws-analytics/script package
  2. Using data attributes - Add data-lwsa-event to any HTML element for automatic click tracking

If you installed the npm package, you can import and call trackEvent() anywhere in your app:

import { trackEvent } from '@lws-analytics/script';
function SignupButton() {
const handleClick = () => {
trackEvent('signup_button_clicked');
};
return <button onClick={handleClick}>Sign up</button>;
}

Add the data-lwsa-event attribute to any element. Clicks are automatically tracked - no JavaScript required:

<button data-lwsa-event="create_account_clicked">Create account</button>
<a href="/pricing" data-lwsa-event="pricing_link_clicked"> See pricing </a>

This works with both the SDK and the script tag approach.

Here’s a complete example demonstrating both methods:

import { trackEvent } from '@lws-analytics/script';
function ExampleForm() {
const handleSubmit = (e) => {
e.preventDefault();
trackEvent('form_submitted');
console.log('Form submitted');
};
return (
<form onSubmit={handleSubmit}>
<input type="email" placeholder="Enter your email" />
{/* Data attribute: tracks when the button is clicked */}
<button type="submit" data-lwsa-event="create_account_button">
Create account
</button>
{/* trackEvent(): tracks when the form is submitted */}
</form>
);
}

In these examples:

  • The data-lwsa-event="create_account_button" attribute automatically tracks when the button is clicked
  • The trackEvent() (SDK) or window.LwsAnalytics.trackCustomEvent() (script tag) function call programmatically tracks when the form is submitted