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

Discussion on the Issues of Image Button Submission and Form Repeated Submission

In many cases, in order to beautify the form, the ...

SVN installation and basic operation (graphic tutorial)

Table of contents 1. What is SVN 2. Svn server an...

Detailed graphic explanation of how to use svg in vue3+vite project

Today, in the practice of vue3+vite project, when...

MySQL fuzzy query statement collection

SQL fuzzy query statement The general fuzzy state...

Tips and precautions for using MySQL index

1. The role of index In general application syste...

Summary of various forms of applying CSS styles in web pages

1. Inline style, placed in <body></body&g...

mysql8.0.11 winx64 installation and configuration tutorial

The installation tutorial of mysql 8.0.11 winx64 ...

The easiest way to reset mysql root password

My mysql version is MYSQL V5.7.9, please use the ...

Example of using Nginx reverse proxy to go-fastdfs

background go-fastdfs is a distributed file syste...

Linux remote login implementation tutorial analysis

Linux is generally used as a server, and the serv...

How to use MySQL DATEDIFF function to get the time interval between two dates

describe Returns the time interval between two da...

Detailed explanation of putting common nginx commands into shell scripts

1. Create a folder to store nginx shell scripts /...

Detailed explanation of this pointing problem in JavaScript

Preface The this pointer in JS has always been a ...

MySql 8.0.11-Winxp64 (free installation version) configuration tutorial

1. Unzip the zip package to the installation dire...