Skip to content

Commit

Permalink
feat(telemetry): measure 25%/50%/75% scroll depth (#11041)
Browse files Browse the repository at this point in the history
GA4 already measures 90%, and we instrument measurements for
25%/50%/75% to better understand how far users scroll.
  • Loading branch information
caugner authored May 2, 2024
1 parent 56a8ee5 commit 4585241
Showing 1 changed file with 45 additions and 0 deletions.
45 changes: 45 additions & 0 deletions client/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import { TopPlacement } from "./ui/organisms/placement";
import { Blog } from "./blog";
import { Newsletter } from "./newsletter";
import { Curriculum } from "./curriculum";
import { useGA } from "./ga-context";

const AllFlaws = React.lazy(() => import("./flaws"));
const Translations = React.lazy(() => import("./translations"));
Expand Down Expand Up @@ -135,6 +136,7 @@ export function App(appProps: HydrationData) {

usePing();
useGleanPage(pageNotFound, appProps.doc);
useScrollDepthMeasurement();

const localeMatch = useMatch("/:locale/*");

Expand Down Expand Up @@ -349,3 +351,46 @@ export function App(appProps: HydrationData) {
);
return routes;
}

function useScrollDepthMeasurement(thresholds = [25, 50, 75]) {
const timeoutID = React.useRef<number | null>();
const [currentDepth, setScrollDepth] = React.useState(0);
const { gtag } = useGA();

useEffect(() => {
const listener = () => {
if (timeoutID.current) {
window.clearTimeout(timeoutID.current);
}
timeoutID.current = window.setTimeout(() => {
const { scrollHeight } = document.documentElement;
const { innerHeight, scrollY } = window;
const scrollPosition = innerHeight + scrollY;
const depth = (100 * scrollPosition) / scrollHeight;

const matchingThresholds = thresholds.filter(
(threshold) => currentDepth < threshold && threshold <= depth
);

matchingThresholds.forEach((threshold) => {
gtag("event", "scroll", {
percent_scrolled: String(threshold),
});
});

const lastThreshold = matchingThresholds.at(-1);
if (lastThreshold) {
setScrollDepth(lastThreshold);
}

timeoutID.current = null;
}, 100);
};

window.addEventListener("scroll", listener);

return () => window.removeEventListener("scroll", listener);
});

return currentDepth;
}

0 comments on commit 4585241

Please sign in to comment.