JS: Add tracking to Plausible for roll percentage
Implementing scroll percentage tracking on your website can give you valuable insights into how users interact with your content. I've created this code snippet that adds scroll percentage tracking and sends the data to Plausible Analytics, where we store the scroll percentage as events with a prop name.
First of all, you need to have Plausible Analytics integrated on your website with event tracking. With this in place, you can create a function that sends events to Plausible every time a user scrolls down your page.
Here is my JavaScript function that adds tracking and sends the data to Plausibe. You can of course add all sorts of events, but in this case it's only scrolling.
function initScrollPlausibleTracking() {
let plausibleLoaded = false;
// Function that waits for Plausible and sends events
function checkIfPlausibleLoaded() {
if (typeof window.plausible === "function") {
plausibleLoaded = true;
console.log("Plausible is loaded");
// Start scroll tracking when Plausible is ready
startScrollTracking();
} else {
// If Plausible is not loaded yet, try again
setTimeout(checkIfPlausibleLoaded, 100);
}
}
// Call checkIfPlausibleLoaded to make sure Plausible is ready
checkIfPlausibleLoaded();
// Calculate the scroll percentage and send events to Plausible
function trackScrollDepth() {
const scrollPercentage = ((window.scrollY + window.innerHeight) / document.body.scrollHeight) * 100;
const thresholds = [20, 40, 60, 80, 90];
thresholds.forEach((threshold) => {
if (scrollPercentage >= threshold) {
plausible("LENC", {
props: {
scroll-percentage: `${threshold}%`
}
});
console.log(`Scroll percentage: ${threshold}%`);
}
});
}
function startScrollTracking() {
document.addEventListener("scroll", trackScrollDepth);
window.addEventListener("resize", trackScrollDepth);
window.addEventListener("load", trackScrollDepth);
}
}
initScrollPlausibleTracking();
checkIfPlausibleLoaded: This function waits for Plausible to be fully loaded before we start scroll tracking. If Plausible is not ready, we try again every 100ms until it is.
Roll percentage calculation: Each time the user scrolls, the current scroll percentage is calculated as a percentage of the page.
Thresholds: We define some specific roll percentages (10%, 20%, 40%, etc.) where we want to track events.
Plausible event: When the user reaches one of these limits, an event is sent to Plausible with category as "Scroll" and value as the specific scroll percentage.
Event listeners: We set up events to listen for scroll, resize and load to ensure that tracking works correctly when the page is loaded or changed.
Once you have added the code to your website, tracking will start working and you will be able to see the collected data in your Plausible Analytics account if your Plausible tracking allows event tracking.
Remove if necessary console.log elements to avoid them appearing in the console, but very good for testing.