How to use JS to check if an element is within the viewport

How to use JS to check if an element is within the viewport

Preface

Share two methods to monitor whether an element is within the viewport

1. Position calculation

Use the Element.getBoundingClientRect() method to return the position of the element relative to the viewport

const isElementVisible = (el) => {
 const rect = el.getBoundingClientRect();
};

Get the width and height of the browser window

const isElementVisible = (el) => {
 const rect = el.getBoundingClientRect();
  const vWidth = window.innerWidth || document.documentElement.clientWidth;
  const vHeight = window.innerHeight || document.documentElement.clientHeight;
};

Determine whether the element is within the viewport, as shown in the figure

const isElementVisible = (el) => {
  const rect = el.getBoundingClientRect()
  const vWidth = window.innerWidth || document.documentElement.clientWidth
  const vHeight = window.innerHeight || document.documentElement.clientHeight

  
  if (
    rect.right < 0 ||
    rect.bottom < 0 ||
    rect.left > vWidth ||
    rect.top > vHeight
  ) {
    return false
  }

  return true
}

The getBoundingClientRect method will cause the browser to reflow and redraw, which consumes slightly more performance, but has better compatibility than Intersection Observer.

2. Intersection Observer

The Intersection Observer API provides a way to asynchronously observe changes in the intersection of a target element with an ancestor element or with a top-level document's viewport.

The Intersection Observer API provides a way to asynchronously detect changes in the intersection of a target element with an ancestor element or the viewport. The configured callback function is triggered when the target element intersects the viewport or other specified elements.

// Get the elements to monitor const boxes = document.querySelectorAll('.box')

// Create an observer and configure the callback function // Use the isIntersecting property to determine whether the element intersects with the viewport const observer = new IntersectionObserver((entries, observer) => {
 entries.forEach((entry) => {
    console.log(
      entry.target,
      entry.isIntersecting ? "visible" : "invisible"
    );
  });
})

boxes.forEach((box) => {
  observer.observe(box);
});

refer to

how-to-check-an-element-is-in-viewport-4bcl

Intersection Observer API

Summarize

This concludes this article on how to use JS to check if an element is within the viewport. For more information about how to use JS to check if an element is within the viewport, please search previous articles on 123WORDPRESS.COM or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

<<:  Detailed explanation of routing configuration in Linux system with multiple network cards

>>:  Examples of the correct way to use AES_ENCRYPT() and AES_DECRYPT() to encrypt and decrypt MySQL

Recommend

How to enhance Linux and Unix server security

Network security is a very important topic, and t...

JavaScript to achieve the effect of clicking on the self-made menu

This article shares the specific code of JavaScri...

Some basic instructions of docker

Table of contents Some basic instructions 1. Chec...

Basic reference types of JavaScript advanced programming

Table of contents 1. Date 2. RegExp 3. Original p...

Sample code for CSS dynamic loading bar effect

Using the knowledge of CSS variables, I will dire...

Let's learn about MySQL database

Table of contents 1. What is a database? 2. Class...

MySQL5.6.31 winx64.zip installation and configuration tutorial

#1. Download # #2. Unzip to local and modify nece...

Detailed explanation of VueRouter routing

Table of contents vue router 1. Understand the co...

Configure VIM as a C++ development editor in Ubuntu

1. Copy the configuration file to the user enviro...

Pure CSS to achieve the effect of picture blinds display example

First, let me show you the finished effect Main i...

Example of using negative margin to achieve average layout in CSS

For evenly distributed layouts, we generally use ...

Complete steps for using Echarts and sub-packaging in WeChat Mini Program

Preface Although the holiday is over, it shows up...

Use of js optional chaining operator

Preface The optional chaining operator (?.) allow...

CentOS method to modify the default ssh port number example

The default ssh port number of Linux servers is g...

Docker uses Supervisor to manage process operations

A Docker container starts a single process when i...