DEV Community

Pelumi Aleshinloye
Pelumi Aleshinloye

Posted on • Originally published at pelumicodes.com

1 1

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

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay