Skip to content

Instantly share code, notes, and snippets.

@iqbalrony
Last active May 14, 2020 07:14
Show Gist options
  • Save iqbalrony/012e0fb27b942f9a84788c9203f9967c to your computer and use it in GitHub Desktop.
Save iqbalrony/012e0fb27b942f9a84788c9203f9967c to your computer and use it in GitHub Desktop.
Determine that target element is in viewport or not by vanilla javascript and jQuery. ( view port, in window view, is visible )
( function($){
"use strict";
// By JavaScript
var $target = document.querySelector('.targetClass');
var setPosition = function ($target) {
var docViewHeight = window.innerHeight;
var docViewTop = window.scrollY;
var docViewBottom = docViewTop + docViewHeight;
var eHeight = $target.offsetHeight;
var eTop = $target.offsetTop;
var eBottom = eTop + eHeight;
return ((eTop <= docViewBottom) && (eBottom >= docViewTop));
}
setPosition($target);
window.addEventListener('scroll', function () {
if(setPosition($target)){
console.log('In the viewport!');
} else {
console.log('Not in the viewport.');
}
},{once:true});
// By jQuery
var $target = $('.targetClass'),
once = false;
var setPosition = function ($target) {
var docViewHeight = $(window).height();
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + docViewHeight;
var eHeight = $target.outerHeight();
var eTop = $target.offset().top;
var eBottom = eTop + eHeight;
return ((eTop <= docViewBottom) && (eBottom >= docViewTop));
}
setPosition($target);
$(window).on('scroll', function (e){
if(setPosition($target)){
console.log('In the viewport!');
} else {
console.log('Not in the viewport.');
}
if(!once){
$( this ).off( e );
}
});
// is the target element fully in viewport?
function isInViewport(elem) {
var bounding = elem.getBoundingClientRect();
return (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
bounding.right <= (window.innerWidth || document.documentElement.clientWidth)
);
};
var item = document.querySelector('.targetClass');
window.addEventListener('scroll', function(e){
if ( isInViewport(item) ) {
console.log('Fully in the viewport!');
} else {
console.log('Not fully in the viewport');
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment