detect if element touches top code example
Example 1: add class when element in viewport vanilla javascript
window.addEventListener('scroll', function (event) {
if (isInViewport(theElementToWatch)) {
}
}, false);
Example 2: add class when element in viewport vanilla javascript
function isInViewPort(element) {
var bounding = element.getBoundingClientRect();
if (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.right <= (window.innerWidth || document.documentElement.clientWidth) &&
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight)
) {
console.log('In the viewport! :)');
return true;
} else {
console.log('Not in the viewport. :(');
return false;
}
}