Detecting if an element is in the Viewport : jQuery

Boy with Silver Wings
Talk Like
Published in
2 min readJan 1, 2017

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

  1. https://github.com/customd/jquery-visible
  2. http://www.appelsiini.net/projects/viewport

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:

  • elementTop : Top position of the element.
  • offset function is used to find the position relative to parent element(body in this case) and top refers to the distance from the top.
  • elementBottom: Bottom position of element
  • To find the bottom position of element we have to add the height of the element to the elementTop variable. Luckily for us jQuery provides a method called outerHeight which allows us to find the height of element including border, padding and optionally padding.
  • viewportTop: Top of the Viewport
  • Can be found with the scrollTop function on window object. Conveniently returns the relative position from the scrollbar position to object matched, which in this case is our window.
  • viewportBottom: Bottom of Viewport
  • Same as elementBottom. We add height of window to the viewportTop to find bottom.

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

--

--