Last active
March 5, 2019 14:50
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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