Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(telemetry): measure 25%/50%/75% scroll depth #11041

Merged
merged 1 commit into from
May 2, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
}
Loading