How to check if element is visible after scrolling?
This should do the trick:
function isScrolledIntoView(elem){ var docViewTop = $(window).scrollTop(); var docViewBottom = docViewTop + $(window).height(); var elemTop = $(elem).offset().top; var elemBottom = elemTop + $(elem).height(); return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));}
Simple Utility FunctionThis will allow you to call a utility function that accepts the element you're looking for and if you want the element to be fully in view or partially.
function Utils() {}Utils.prototype = { constructor: Utils, isElementInView: function (element, fullyInView) { var pageTop = $(window).scrollTop(); var pageBottom = pageTop + $(window).height(); var elementTop = $(element).offset().top; var elementBottom = elementTop + $(element).height(); if (fullyInView === true) { return ((pageTop < elementTop) && (pageBottom > elementBottom)); } else { return ((elementTop <= pageBottom) && (elementBottom >= pageTop)); } }};var Utils = new Utils();
Usage
var isElementInView = Utils.isElementInView($('#flyout-left-container'), false);if (isElementInView) { console.log('in view');} else { console.log('out of view');}
This answer in Vanilla:
function isScrolledIntoView(el) { var rect = el.getBoundingClientRect(); var elemTop = rect.top; var elemBottom = rect.bottom; // Only completely visible elements return true: var isVisible = (elemTop >= 0) && (elemBottom <= window.innerHeight); // Partially visible elements return true: //isVisible = elemTop < window.innerHeight && elemBottom >= 0; return isVisible;}
Update: use IntersectionObserver
The best method I have found so far is the jQuery appear plugin. Works like a charm.
Mimics a custom "appear" event, which fires when an element scrolls into view or otherwise becomes visible to the user.
$('#foo').appear(function() { $(this).text('Hello world');});
This plugin can be used to prevent unnecessary requests for content that's hidden or outside the viewable area.