docbrown/app/javascript/utilities/viewport.js
rhymes f9506affb5
Use faster JS selection methods (#11409)
* Add JS tips section to frontend documentation

* Replace document.getElementsByTagName('body') with document.body

* Replace querySelectorAll with faster selecting methods where appropriate

* Replace querySelector with faster selecting methods where appropriate

* Fix typo

* Fix forEach and getElementsByClassName

* Change querySelector* to faster methods in erb files

* Change querySelector* to faster methods in ruby files

* Fix runkit tag

* Various fixes

* Update app/assets/javascripts/initializers/initializeEllipsisMenu.js

Co-authored-by: Ridhwana <Ridhwana.Khan16@gmail.com>

* Update app/assets/javascripts/utilities/slideSidebar.js

Co-authored-by: Ridhwana <Ridhwana.Khan16@gmail.com>

* Commenting out flaky spec

Co-authored-by: Ridhwana <Ridhwana.Khan16@gmail.com>
2020-11-16 17:35:50 +01:00

24 lines
849 B
JavaScript

/**
* Checks if an element is visible in the viewport
*
* @example
* const element = document.getElementById('element');
* isInViewport(element); // true or false
*
* @param {object} element - The HTML element to check
* @param {number} [offsetTop=0] - Part of the screen to ignore counting from the top
*
* @returns {boolean} isInViewport - true if the element is visible in the viewport
*/
export function isInViewport(element, offsetTop = 0) {
const boundingRect = element.getBoundingClientRect();
const clientHeight =
window.innerHeight || document.documentElement.clientHeight;
const clientWidth = window.innerWidth || document.documentElement.clientWidth;
return (
boundingRect.top >= offsetTop &&
boundingRect.left >= 0 &&
boundingRect.bottom <= clientHeight &&
boundingRect.right <= clientWidth
);
}