Javascript if element is in viewport

How to test if an element is in the viewport with vanilla JavaScript

Today, I want to show you how to write a small vanilla JS helper function to check if an element is in the viewport.

“In the viewport” means in the visible part of the screen, as opposed to above or below the visible area. This is useful when doing things like creating lazy loading scripts.

Getting the bounding coordinates

At the heart of our function is Element.getBoundingClientRect() , which provides an element’s position within the viewport. It returns an object with an element’s height and width, as well as it’s distance from the top, bottom, left, and right of the viewport.

// Get the H1 heading var h1 = document.querySelector('h1'); // Get it's position in the viewport var bounding = h1.getBoundingClientRect(); // Log the results console.log(bounding); //  // height: 118, // width: 591.359375, // top: 137, // bottom: 255, // left: 40.3125, // right: 631.671875 // > 

Determining if the element is in the viewport

If an element is in the viewport, it’s position from the top and left will always be greater than or equal to 0 . It’s distance from the right will be less than or equal to the total width of the viewport, and it’s distance from the bottom will be less than or equal to the height of the viewport.

There are two ways to check the viewport’s width. Some browsers support window.innerWidth , other’s support document.documentElement.clientWidth , and some support both. We can try one and fallback to the other by doing something like this:

(window.innerWidth || document.documentElement.clientWidth) 

Similarly, to get the viewport height, we can use window.innerHeight in some browsers and document.documentElement.clientHeight in others. Like with width, we can try one and fallback to the other:

(window.innerHeight || document.documentElement.clientHeight) 

Putting it all together

Let’s use that heading from earlier as an example.

// Get the H1 heading var h1 = document.querySelector('h1'); // Get it's position in the viewport var bounding = h1.getBoundingClientRect(); // Log the results console.log(bounding); //  // height: 118, // width: 591.359375, // top: 137, // bottom: 255, // left: 40.3125, // right: 631.671875 // > 

We can check if the element is in the viewport like this.

if ( bounding.top >= 0 && bounding.left >= 0 && bounding.right  (window.innerWidth || document.documentElement.clientWidth) && bounding.bottom  (window.innerHeight || document.documentElement.clientHeight) )  console.log('In the viewport!'); > else  console.log('Not in the viewport. whomp whomp'); > 

That’s super clunky to have to write out each time though, so this kind of thing deserves it’s own helper function.

var isInViewport = function (elem)  var bounding = elem.getBoundingClientRect(); return ( bounding.top >= 0 && bounding.left >= 0 && bounding.bottom  (window.innerHeight || document.documentElement.clientHeight) && bounding.right  (window.innerWidth || document.documentElement.clientWidth) ); >; 

We can pass in our element, and isInViewport() will get the bounding coordinates and run our check. It returns true if it’s in the viewport, and false if it’s not.

var h1 = document.querySelector('h1'); if (isInViewport(h1))  // Do something. > 

Using the helper method

One way I’ve put this to use is in a lazy loading script. I listen for scroll events, and check if my image is in the viewport on scroll. If it is, I load it.

Here’s a really simplified version…

var image = document.querySelector('[data-image]'); window.addEventListener('scroll', function (event)  if (isInViewport(image))  image.innerHTML = ' '; > >, false); 

Hate the complexity of modern front‑end web development? I send out a short email each weekday on how to build a simpler, more resilient web. Join over 14k others.

Made with ❤️ in Massachusetts. Unless otherwise noted, all code is free to use under the MIT License. I also very irregularly share non-coding thoughts.

Источник

Check If Element Is Inside Of The Viewport With JavaScript

Let’s have a look at how we can check if a certain element on the page is partially or fully inside of the viewport. This could be used for a lot of things, a classic use case would be lazy loading images. Another use case could be to trigger an animation when the element comes into the viewport.

First we need to find out how far from the edges of the viewport the element is currently positioned by using JavaScript’s function getBoundingClientRect() .

To find out if the whole element is inside of the viewport we can simply check if the top and left value is bigger or equal to 0, that the right value is less or equal to the viewport height ie window.innerWidth and that the bottom value is less or equal to window.innerHeight .

var myElement = document.getElementById('my-element'); var bounding = myElement.getBoundingClientRect(); if (bounding.top >= 0 && bounding.left >= 0 && bounding.right else

Something to keep in mind is that window.innerWidth and window.innerHeight doesn’t work in all browsers. To make sure this doesn’t break in those browsers, let’s use document.documentElement.clientWidth and document.documentElement.clientHeight .

We write the following, which falls back to document.documentElement.clientWidth if window.innerWidth is not supported:

And so the final code to check if the whole element is inside of the viewport is:

var myElement = document.getElementById('my-element'); var bounding = myElement.getBoundingClientRect(); function elementInViewport() < var bounding = myElement.getBoundingClientRect(); if (bounding.top >= 0 && bounding.left >= 0 && bounding.right else < console.log('Element is NOT in the viewport!'); >>

Check if part of element is in the viewport

In most cases, I think it makes more sense to find out if any part of the element is inside of the viewport, especially in the case of lazy loading images. So let’s do that.

Let’s grab the width and height of our element using myElement .offsetWidth and myElement.offsetHeight .

var myElement = document.getElementById('my-element'); var bounding = myElement.getBoundingClientRect(); var myElementHeight = myElement.offsetHeight; var myElementWidth = myElement.offsetWidth; function elementInViewport() < var bounding = myElement.getBoundingClientRect(); if (bounding.top >= -myElementHeight && bounding.left >= -myElementWidth && bounding.right else < console.log('Element is NOT in the viewport!'); >>

Try it in the CodePen below – scroll up, down and sideways and hit the check button to see if part of the element is in the viewport:

Источник

Check If an Element is Visible in the Viewport

Summary: in this tutorial, you’ll learn how to check if an element is visible in the viewport using JavaScript.

When an element is in the viewport, it appears in the visible part of the screen.

To check if an element is visible in the viewport, you use the following isInViewport() helper function:

function isInViewport(element) < const rect = element.getBoundingClientRect(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom window.innerHeight || document.documentElement.clientHeight) && rect.right window.innerWidth || document.documentElement.clientWidth) ); > Code language: JavaScript (javascript)

If the element is in the viewport, the function returns true . Otherwise, it returns false .

Checking if an element is visible in the viewport has many applications, for example:

  • Perform lazy loading images. You only load the image if its container is visible in the current viewport. This increases the loading speed of the page.
  • Load a script to show the ads if it is in the viewport. This saves the advertisers a lot of money spending for impressions that users may not see the below-the-fold ads.

Let’s dive into the isInViewport() function to understand how it works.

Getting the relative position of an element

The method element.getBoundingClientRect() provides the element’s position and its relative position to the viewport.

It returns an object that includes element’s height, width, and its distance from the top, left, bottom, and right of the viewport.

Check If an Element is Visible in the Viewport

Suppose that you have element as follows:

div class="box"> div>Code language: HTML, XML (xml)

To get the element’s position in the viewport, you use the getBoundingClientRect() method:

const box = document.querySelector('.box'); const rect = box.getBoundingClientRect(); console.log(rect); Code language: JavaScript (javascript)
< x: 100 y: 182 width: 300 height: 250 top: 182 right: 400 bottom: 432 left: 100 > Code language: CSS (css)

If the element is in the viewport, its top and left are always greater than or equal zero. In addition, its distance from the right is less than or equal to the width of the viewport, and ids distance from the bottom is less than or equal to the height of the viewport.

To get the width the height of the viewport, you use the window.innerWidth and window.innerHeight in modern browsers. Some browsers, however, use the document.documentElement.clientWidth and document.documentElement.clientHeight .

To support all browsers, you can try one and fallback to other, like this:

const viewportWidth = window.innerWidth || document.documentElement.clientWidth; const viewportHeight = window.innerHeight || document.documentElement.clientHeight;Code language: JavaScript (javascript)

The following detects if the element is in the viewport:

const box = document.querySelector('.box'); const rect = box.getBoundingClientRect(); const isInViewport = rect.top >= 0 && rect.left >= 0 && rect.bottom window.innerHeight || document.documentElement.clientHeight) && rect.right window.innerWidth || document.documentElement.clientWidth); console.log(isInViewport);Code language: JavaScript (javascript)

Hence, you can wrap the logic in a helper function isInViewport() and use it as follows:

const box = document.querySelector('.box'); const result = isInViewport(box);Code language: JavaScript (javascript)

When you scroll the document, the box will not be in the viewport. To monitor this, you can listen to the scroll event and show the result in another div element.

The following show the HTML page:

html> html lang="en"> head> meta charset="UTF-8"> title>Check if an element is visible in the viewport title> link rel="stylesheet" href="css/style-viewport.css"> head> body> div class="box"> div> div id="message">Please scroll to check if the box is visible div> script src="js/app.js"> script> body> html>Code language: HTML, XML (xml)

Here is the JavaScript file:

function isInViewport(el) < const rect = el.getBoundingClientRect(); return ( rect.top >= 0 && rect.left >= 0 && rect.bottom window.innerHeight || document.documentElement.clientHeight) && rect.right window.innerWidth || document.documentElement.clientWidth) ); > const box = document.querySelector('.box'); const message = document.querySelector('#message'); document.addEventListener('scroll', function ( ) < const messageText = isInViewport(box) ? 'The box is visible in the viewport' : 'The box is not visible in the viewport'; message.textContent = messageText; >, < passive: true >); Code language: JavaScript (javascript)

Summary

  • Use the getBoundingClientRect() method to get the size of the element and its relative position to the viewport.
  • Compare the position of the element with the viewport height and width to check if the element is visible in the viewport or not.

Источник

Best Way to Detect if Element is in Viewport – Using Intersection Observer API

detect if element is in viewport,intersection observer api,lazy-loading images,infinite scrolling,browser api

Hello Friends 🙏, As a Frontend developer, most of us must have got into situation where we need to 👀 detect if element is in viewport and then do some actions based on it.

This is not an easy task as it involves lot of calculations in JavaScript code 😅, which is mostly unreliable and prone to causing the browser sluggish as all those calculations run on the main thread 😵.

To overcome this situation, browsers has developed Intersection Observer API 😎, this browser API asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document’s viewport.

Common use cases that can be acheived using this Intersection Observer API are:

  • ✅ “Lazy-loading images” or other content as a page is scrolled.
  • ✅ Implementing “infinite scrolling” web sites.
  • “Deciding animation start/stop” on elements, based on its visibility to a user.
  • ✅ “Auto-pause video” when it’s out of view
  • ✅ “Detect how much content is viewed“, trigger functionality when all content is viewed.

With Intersection Observer API, we can register a callback function, which gets executed whenever an element enters or exits another element or the viewport. It basically tells about the amount of the element getting intersected in percentage.

This tutorial answers the below questions:
– how to check if element is in viewport react
– check if element is partially in viewport
– check if element is visible on screen javascript

How to Detect if Element is in Viewport

detect if element is in viewport,intersection observer api,lazy-loading images,infinite scrolling,browser api

detect if element is in viewport,intersection observer api,lazy-loading images,infinite scrolling,browser api

Liked this tutorial? Check more here -> Browser Turorials.

Источник

Читайте также:  Python datetime strptime format
Оцените статью