Skip to content

Instantly share code, notes, and snippets.

@rizkysyazuli
Last active February 20, 2020 11:30
Show Gist options
  • Save rizkysyazuli/8535011 to your computer and use it in GitHub Desktop.
Save rizkysyazuli/8535011 to your computer and use it in GitHub Desktop.
[JavaScript - Check if element in viewport] A function to detect if a "page" element is visible in the browser viewport. It was used on a single-page website i made for changing the address, lazy-loading assets and updating the navigation menu. #javascript #jquery
function range() {
// the outer most container element that wraps the pages
var $viewport = $('.viewport');
// the container element for each pages
var $page = $('.page');
// viewport dimension
var viewX = $viewport.scrollLeft(),
viewY = $viewport.scrollTop(),
viewWidth = $viewport.width(),
viewHeight = $viewport.height();
// viewport center points
var coreX = viewX + (viewWidth / 2),
coreY = viewY + (viewHeight / 2);
$page.each(function() {
// get page position & dimension
var $el = $(this),
pageX = $el.position().left,
pageY = $el.position().top,
pageWidth = $el.width(),
pageHeight = $el.height();
// check if page is visible
if (viewX < (pageX + pageWidth) && (viewX + viewWidth) > pageX &&
(viewY + viewHeight) > pageY && viewY < (pageY + pageHeight)) {
// do stuff here. you can use the $el variable
}
// check if a page is at the center
if (coreX > pageX && coreX < (pageX + pageWidth) &&
coreY > pageY && coreY < (pageY + pageHeight)) {
// do more stuff here. you can use the $el variable
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment