Skip to content

Instantly share code, notes, and snippets.

@kahl-dev
Created September 8, 2017 18:01
Show Gist options
  • Save kahl-dev/eb0a1d41d19bc176101f872107f90330 to your computer and use it in GitHub Desktop.
Save kahl-dev/eb0a1d41d19bc176101f872107f90330 to your computer and use it in GitHub Desktop.
ES6 event for changing state of is in viewport or not
function isElementInViewport(el) {
const rect = el.getBoundingClientRect();
const viewPortHeight =
window.innerHeight || document.documentElement.clientHeight;
const topBottom =
(rect.top > 0 && rect.top < viewPortHeight) ||
(rect.bottom > 0 && rect.bottom < viewPortHeight) ||
(rect.top <= 0 && rect.height + rect.top >= viewPortHeight);
// @TODO LeftRight
return topBottom;
}
function onVisibilityChange(el, fn, threshhold = 250, scope) {
let last, deferTimer, old_visible;
return function() {
const context = scope || this;
const now = +new Date();
const args = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function() {
last = now;
const visible = isElementInViewport(el);
if (visible != old_visible) {
old_visible = visible;
fn.apply(context, [...args, visible]);
}
}, threshhold);
} else {
last = now;
const visible = isElementInViewport(el);
if (visible != old_visible) {
old_visible = visible;
fn.apply(context, [...args, visible]);
}
}
};
}
['DOMContentLoaded', 'load', 'resize', 'wheel'].forEach(eventHandler =>
document.addEventListener(eventHandler, onVisibilityChange(
document.querySelector('.test'), (e, isVisible) => {
if (isVisible) {
// Do something on enter viewport
} else {
// Do something on leaving viewport
}
}, 250, this)
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment