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

Solve the problem of inconsistent MySQL storage time

After obtaining the system time using Java and st...

SQL implementation of LeetCode (175. Joining two tables)

[LeetCode] 175.Combine Two Tables Table: Person +...

Pure CSS to achieve candle melting (water droplets) sample code

Achieve results Implementation ideas The melting ...

MySQL installation and configuration tutorial for Mac

This article shares the MySQL installation tutori...

In-depth understanding of JavaScript callback functions

Table of contents Preface Quick Review: JavaScrip...

JS realizes video barrage effect

Use ES6 modular development and observer mode to ...

Vue implements button switching picture

This article example shares the specific code of ...

Detailed installation process of MySQL 8.0 Windows zip package version

The installation process of MySQL 8.0 Windows zip...

A brief analysis of the best way to deal with forgotten MySQL 8 passwords

Preface Readers who are familiar with MySQL may f...

Solve the problem that ElementUI custom CSS style does not take effect

For example, there is an input box <el-input r...

Application of Hadoop counters and data cleaning

Data cleaning (ETL) Before running the core busin...

Native js to achieve puzzle effect

This article shares the specific code of native j...

Linux file and user management practice

1. Display the files or directories in the /etc d...