Skip to content

Instantly share code, notes, and snippets.

@iqbalrony
Last active May 14, 2020 07:14
Show Gist options
  • Select an option

  • Save iqbalrony/012e0fb27b942f9a84788c9203f9967c to your computer and use it in GitHub Desktop.

Select an option

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'),
docViewHeight,
docViewTop,
docViewBottom,
eHeight,
eTop,
eBottom;
var setPosition = function () {
docViewHeight = window.innerHeight;
docViewTop = window.scrollY;
docViewBottom = docViewTop + docViewHeight;
eHeight = $target.offsetHeight;
eTop = $target.offsetTop;
eBottom = eTop + eHeight;
return;
}
setPosition();
var isInView = function () {
return ((eTop <= docViewBottom) && (eBottom >= docViewTop));
}
window.addEventListener('scroll', function () {
setPosition();
if(isInView()){
console.log('In the viewport!');
} else {
console.log('Not in the viewport.');
}
},{once:true});
// By JavaScript
var $target = document.querySelector('.targetClass'),
docViewHeight,
docViewTop,
docViewBottom,
eHeight,
eTop,
eBottom;
var setPosition = function () {
docViewHeight = window)
docViewTop = window.scrollY;
docViewBottom = docViewTop + docViewHeight;
eHeight = $target.offsetHeight;
eTop = $target.offsetTop;
eBottom = eTop + eHeight;
return;
}
setPosition();
var isInView = function () {
return ((eTop <= docViewBottom) && (eBottom >= docViewTop));
}
$(window).on('scroll', function (e){
setPosition();
if(isInView()){
console.log('In the viewport!');
} else {
console.log('Not in the viewport.');
}
$( this ).off( e );
},{once:true});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment