Last active
May 14, 2020 07:14
-
-
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 )
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ( 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