Detecting if an element is in the Viewport : jQuery

Detect if an element is visible in the view port. Now why would any one in the right mind want to do that? Well you are reading this, so may be you know why.

Small Experiment on Codepen

I have to warn you that there are already plugins that help us do the same with jQuery like

While all these exist, how many plugins shall we ship with our website? How is the user going to cache them all? Let’s take a peek into how this is done.

PS: I’m not going to be talking about jQuery :visible selector. This selector selects elements based on display CSS property or opacity.

We are going to be discussing how to detect if an element is visible on screen in real time.

Here is a codepen demo of what we will be doing.

This started with this question on Stackoverflow for which my answer is here.

It has been made to suit the question with some borrowed code from this stackoverflow answer.

Enough with the How I got here lesson. Getting to the JS part.

$.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;
};

This forms the part of JS that concerns us most. To check if an element is in the viewport, we need four variables.
These being:

All that is left is to find if the element is within the window coordinates.

]
$(window).on(‘resize scroll’, function() {
//Code here
});

By wrapping the elements required on a resize, scroll event, we have successfully build the platform to find if an element is in the viewport or not.

Happy Coding

Talk Like

A Matter of Space and Time

Boy with Silver Wings

Written by

Engineer. Driven by Passion.

Talk Like

Talk Like

A Matter of Space and Time