Skip to content

Instantly share code, notes, and snippets.

@audunolsen
Last active March 5, 2019 14:50
Show Gist options
  • Save audunolsen/25030f363093e6138d2dd633d50a60b8 to your computer and use it in GitHub Desktop.
Save audunolsen/25030f363093e6138d2dd633d50a60b8 to your computer and use it in GitHub Desktop.
Check if any part of element is visible inside viewport – vertical only, one-liner.
/* Check if any part of element is visible inside viewport – vertical only, one-liner.
*
* Inspired by @StokeMasterJack's reply to a gist thread about element visibility inside the browser:
* https://gist.github.com/davidtheclark/5515733#gistcomment-2113205
*
* I needed a vertical only one and wanted to rewrite it to be as short as possible w/
* ES6's destructuring, optional parameters and arrow function implicit returns
*
* @global
* @param1 {HTMLElement} - The element to check if visibile in viewport.
* @param2 {undefined} - Do not pass argument, use defualt value!
* @return {boolean} - True if visible, false if not.
*/
const isInViewport = (e, {top:t, height:h} = e.getBoundingClientRect()) => t <= innerHeight && t + h >= 0;
// —————————————————————— USAGE EXAMPLE ——————————————————————
/* It's not uncommon for webpages to include a fixed sidebar, that at some point should
* stop and become static. E.g. being fixed until you scroll to the footer.
* Here's an example:
*/
const footer = document.querySelector(".footer");
window.addEventListener("scroll", () =>
sidebar.classList.toggle("fixed", !isInViewport(footer)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment