DEV Community

Pelumi Aleshinloye
Pelumi Aleshinloye

Posted on • Originally published at pelumicodes.com

How to test if an element is in the viewport

This article was originally posted on pelumicodes.com

There can be several scenarios that may require you to determine whether an element is currently in the viewport of your browser, you might want to implement lazy loading or animating divs whenever they show up on the user's screen.

We will not be using jQuery :visible selector because it selects elements based on display CSS property or opacity.

To do this with jQuery, we first have to define a function isInViewPort that checks if the element is in the browser's viewport

$.fn.isInViewport = function() {
var elementTop = $(this).offset().top;
var elementBottom = elementTop + $(this).outerHeight();
var viewportTop = $(window).scrollTop();
var viewportBottom = viewportTop + $(window).height();
return elementBottom > viewportTop && elementTop < viewportBottom;
};

$(window).on(resize scroll, function() {
  if ($(.foo).isInViewport()) {
    // code here
  }
});

The elementTop returns the top position of the element, offset().top returns the distance of the current element relative to the top of the offsetParent node.

To get the bottom position of the element we need to add the height of the element to the offset().top . The outerHeight allows us to find the height of the element including the border and padding.

The viewportTop returns the top of the viewport; the relative position from the scrollbar position to object matched.

To get the viewportBottom too we add the height of the window to the viewportTop.

The isInViewport function returns true if the element is in the viewport, so you can run whatever code you want if the condition is met.


Plugins that do the job for you

cc: stackoverflow answer

Top comments (0)