How to Detect if a HTML Element is in the Viewport and Trigger a Function




You might have seen in some websites where an HTML element starts animating or fires some action when it comes to the viewport. So how to detect if an element is in the viewport? Well, here we have shared some useful jQuery plugins to detect whether an HTML element is the viewport or not.

Also read:

List of jQuery Plugins to Detect if an HTML Element is in the Viewport

jQuery InView

jQuery InView helps to detect whether an HTML element is in the viewport or out of it. It comes with nested statement which can be used to call a function when the HTML element comes to the viewport and goes out of it. Below is the code sample of jQuery InView plugin-
$('elementIDorClass').on('inview', function(event, isInView) {
if (isInView) {
// element is now visible in the viewport
} else {
// element has gone out of viewport
}
});

Here is jQuery InView git.

isInViewport

isInViewport is another lightweight jQuery plugin to know if the element is in the viewable area. All you need is to add :in-viewport after the selector to trigger a function or do some action. Below is the code sample of isInViewport jQuery plugin-
$( 'div:in-viewport' ).css( 'background-color', 'red' );

Check out isInViewport git page to download this plugin.

jQuery Appear

jQuery Appear is a tiny plugin to fire a function when an element comes into the document viewport. It is quite easy to use, here is the code sample-
$('elementIDorClass').appear(function() {
$(this).text('Hello world');
});

Check out the GitHub home of jQuery Appear for more info.

How to Know if a HTML Element is on Viewport Without using a Plugin?

Do you want to know if an HTML element is visible on the viewport without using any jQuery plugin? Check out this well explained Stackoverflow answer.



Article by Shrinivas Naik

Hi, This is Shrinivas I am a web developer and WordPress enthusiast. I am also a hobby blogger who loves to write about WordPress, web tools, blogging and technology.


Leave a Reply