diff --git a/src/utils/isInViewPortIntersectionObserver.ts b/src/utils/isInViewPortIntersectionObserver.ts new file mode 100644 index 0000000..50d61c7 --- /dev/null +++ b/src/utils/isInViewPortIntersectionObserver.ts @@ -0,0 +1,43 @@ +export interface InviewPortType { + callback: () => void; + target: HTMLElement | null; + options: IntersectionObserverInit | undefined; + freezeOnceVisible: boolean; +} + +const checkInViewIntersectionObserver = ({ + target, + options = { root: null, rootMargin: `0%`, threshold: 0 }, + callback, + freezeOnceVisible = false, +}: InviewPortType) => { + const _funCallback: IntersectionObserverCallback = ( + entries: IntersectionObserverEntry[], + observer: IntersectionObserver + ) => { + entries.map((entry: IntersectionObserverEntry) => { + if (entry.isIntersecting) { + // + callback(); + // ---- IF TRUE WE WILL UNOBSERVER AND FALSE IS NO + if (freezeOnceVisible) { + observer.unobserve(entry.target); + } + } + return true; + }); + }; + + // _checkBrowserSupport----- + if (typeof window.IntersectionObserver === "undefined") { + console.error( + "window.IntersectionObserver === undefined! => Your Browser is Notsupport" + ); + return; + } + + const observer = new IntersectionObserver(_funCallback, options); + target && observer.observe(target); +}; + +export default checkInViewIntersectionObserver;