Skip to content

Instantly share code, notes, and snippets.

@tak-dcxi
Last active April 24, 2024 10:21
Show Gist options
  • Save tak-dcxi/f6e8dc9a22494609604fa5fe49e44896 to your computer and use it in GitHub Desktop.
Save tak-dcxi/f6e8dc9a22494609604fa5fe49e44896 to your computer and use it in GitHub Desktop.
initializeObserveAnimation
export type ObserverOptions = {
root?: HTMLElement | null;
rootMargin?: string;
threshold?: number | number[];
};
const defaultOptions: ObserverOptions = {
root: null,
rootMargin: "0px",
threshold: 0
};
const initializeObserveAnimation = (
targets: NodeListOf<HTMLElement>,
options: ObserverOptions = {}
): void => {
const targetsLength = targets.length;
if (targetsLength === 0) {
console.error("initializeObserveAnimation: Target elements are not found.");
return;
}
const mergedOptions = { ...defaultOptions, ...options };
const observer = createObserver(mergedOptions, targetsLength);
targets.forEach((target) => observer.observe(target));
};
const createObserver = (
options: ObserverOptions,
targetsLength: number
): IntersectionObserver => {
let observer: IntersectionObserver;
let activeCount = 0;
const handleObserve = (entries: IntersectionObserverEntry[]): void => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
// 要素が画面内に入ったら`data-animated`の値を`true`にする
entry.target.setAttribute("data-animated", "true");
// アニメーションした要素は監視をやめる
observer.unobserve(entry.target);
activeCount++;
}
});
if (activeCount === targetsLength) {
observer.disconnect();
}
};
observer = new IntersectionObserver(handleObserve, options);
return observer;
};
export default initializeObserveAnimation
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment