Last active
April 17, 2020 08:32
-
-
Save koyanloshe/a1190ea6739152f9bcc6aff505fc6bd2 to your computer and use it in GitHub Desktop.
Check if a certain element in the viewport #Javascript
This file contains 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 onVisibilityChange(el, callback) { | |
var old_visible; | |
return function () { | |
var visible = isElementInViewport(el); | |
if (visible != old_visible) { | |
old_visible = visible; | |
if (typeof callback == 'function') { | |
callback(); | |
} | |
} | |
} | |
} | |
var handler = onVisibilityChange(el, function() { | |
/* your code go here */ | |
}); | |
//jQuery | |
$(window).on('DOMContentLoaded load resize scroll', handler); | |
/* //non-jQuery | |
if (window.addEventListener) { | |
addEventListener('DOMContentLoaded', handler, false); | |
addEventListener('load', handler, false); | |
addEventListener('scroll', handler, false); | |
addEventListener('resize', handler, false); | |
} else if (window.attachEvent) { | |
attachEvent('onDOMContentLoaded', handler); // IE9+ :( | |
attachEvent('onload', handler); | |
attachEvent('onscroll', handler); | |
attachEvent('onresize', handler); | |
} | |
*/ |
This file contains 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 isElementInViewport (el) { | |
//special bonus for those using jQuery | |
if (typeof jQuery === "function" && el instanceof jQuery) { | |
el = el[0]; | |
} | |
var rect = el.getBoundingClientRect(); | |
return ( | |
rect.top >= 0 && | |
rect.left >= 0 && | |
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */ | |
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */ | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment