Skip to content

Instantly share code, notes, and snippets.

@qysp
Forked from MakingJamie/in_viewport.js
Last active December 18, 2020 09:36
Show Gist options
  • Select an option

  • Save qysp/488bcd28c1ba9c4600526980d4f31e88 to your computer and use it in GitHub Desktop.

Select an option

Save qysp/488bcd28c1ba9c4600526980d4f31e88 to your computer and use it in GitHub Desktop.
check if element is in viewport - vanilla JS. Use by adding a “scroll” event listener to the window and then calling isInViewport().
const inViewport = (element: Element): boolean => {
const rect = element.getBoundingClientRect();
const html = document.documentElement;
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight ?? html.clientHeight) &&
rect.right <= (window.innerWidth ?? html.clientWidth)
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment