亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Table of Contents
IntersectionObserver Quick Overview
Desktop
Mobile/Tablet
Use Case 1: Lazy loading images
Use Case 2: Automatically pause video when elements leave view
Use Case 3: View how much content has been viewed
Thank you for your participation!
Home Web Front-end CSS Tutorial A Few Functional Uses for Intersection Observer to Know When an Element is in View

A Few Functional Uses for Intersection Observer to Know When an Element is in View

Apr 21, 2025 am 11:19 AM

Intersection Observer API: Real-time monitoring of whether elements are visible

You may not know that JavaScript has quietly accumulated many observers in recent years, and Intersection Observer is one of the powerful tools. Observers are objects that monitor specific events in real time, just as birders sit in their favorite place and wait for the bird to appear. Different observers observe different goals.

The first observer I came into contact with was Mutation Observer, which detects changes to the DOM tree. It was unique at the time, but now we have more observers.

Intersection Observer observes the "intersection" between an element and its ancestor element or the visible area of ??the page (i.e., the viewport) (i.e., the element enters or leaves the viewport). It's a bit like watching a train pass by a station. You can see when the train enters the station, when it leaves the station and how long it has stopped.

Understanding when an element is about to enter the field of view, when it disappears, or how long it has passed since it has entered the field of view is very practical. Therefore, we will learn about some use cases - after the code to create the IntersectionObserver object through the Intersection Observer API.

IntersectionObserver Quick Overview

At the time of writing, the Intersection Observer API has received extensive support.

The browser supports data from Caniuse, which contains more details. The number indicates that the browser supports this feature in this version and later.

Desktop

Mobile/Tablet

However, if you want to check if it is supported when using Intersection Observer, you can check if the IntersectionObserver property exists in the window object:

 if(!!window.IntersectionObserver){}
/* or */
if('IntersectionObserver' in window){}

OK, let’s take a look at the creation of the object:

 var observer = new IntersectionObserver(callback, options);

The constructor of the IntersectionObserver object accepts two parameters. The first is the callback function, which will be executed when the observer notices the intersection and passes some data about the intersection asynchronously.

The second (optional) parameter is options , an object containing information that defines what "cross" is. We may not want to know when the element is about to enter the field of view, but only when it is fully visible. Things like this are defined by the options parameter.

Options has three properties:

  • root – The ancestor element/viewport with which the observed element will cross. Think of it as the station where the train will cross it.
  • rootMargin – The perimeter of the root element, shrinking or enlarging the observation area of ??the root element to detect crossovers. It is similar to the CSS margin property.
  • threshold – an array of values ??(between 0 and 1.0), each representing the distance the element crosses or crosses the root, at which the callback will be triggered.

Suppose our threshold is 0.5. A callback is triggered when an element enters or exceeds its semi-visible threshold. If the value is [0.3, 0.6] , a callback will be triggered when the element enters or exceeds its 30% visible threshold and its 60% visible threshold.

That’s all about the theory now. Let's see some demos. First of all, lazy loading.

Use Case 1: Lazy loading images

To view the load tag , check this page because the embedded demo does not display the tag.

CSS-Tricks has already thoroughly introduced lazy loading, which is usually done like this: display a lightweight placeholder, the image will be displayed at the placeholder's position, and then replace it with the expected image as it enters (or is about to enter) the field of view. Trust me, it's not lazy to implement this at all - that is, until we get some native code to use.

We will apply the same mechanism. First, we have a bunch of images and define a placeholder image that is initially displayed. We use a data attribute to carry the URL of the original image to be displayed, which defines the image to be loaded when the actual image enters the field of view.

<img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/174520555311750.jpg" class="lazy" alt="A Few Functional Uses for Intersection Observer to Know When an Element is in View"><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/174520555481250.jpg" class="lazy" alt="A Few Functional Uses for Intersection Observer to Know When an Element is in View"><img src="/static/imghw/default1.png" data-src="https://img.php.cn/upload/article/000/000/000/174520555431263.jpg" class="lazy" alt="A Few Functional Uses for Intersection Observer to Know When an Element is in View">

The rest are scripts.

 let observer = new IntersectionObserver(
(entries, observer) => { 
  entries.forEach(entry => {
    /* handle each cross here*/
  });
}, 
{rootMargin: "0px 0px -200px 0px"});

The callback function above is an arrow function (although you can use a normal function).

The callback function receives two parameters: a set of entries containing information about each intersection; and the observer itself. These entries can be filtered or looped through, and then process the cross entries we want. As for options, I only provide the rootMargin value, allowing the root and threshold properties to take their default values.

The default value of root is the viewport, and the default value of threshold is 0 - this can be roughly interpreted as "notifying me the moment the element appears in the viewport!"

However, strangely, I used rootMargin to reduce the bottom of the viewport's observation area by 200 pixels. We don't usually do this in lazy loading. Instead, we might increase margins or keep it default. However, in this case, we usually don't reduce margins. I do this just because I want to demonstrate the original image loaded at the threshold of the observation area. Otherwise, all operations will occur out of view.

When the image intersects the viewing area of ??the viewport (200 pixels above the bottom in the demonstration), we replace the placeholder image with the actual image.

 let observer = new IntersectionObserver(
(entries, observer) => { 
entries.forEach(entry => {
    /* Placeholder replacement*/
    entry.target.src = entry.target.dataset.src;
    observer.unobserve(entry.target);
  });
}, 
{rootMargin: "0px 0px -200px 0px"});

entry.target is the element observed by the observer. In our case, these are image elements. Once the placeholder is replaced in the image element, we no longer need to observe it, so we call the observer's unobserve method on it.

Now that the observer is ready, it's time to start observing all images using its observe method:

 document.querySelectorAll('img').forEach(img => { observer.observe(img) });

That's it! We've lazy to load the image. Go to the next demo.

Use Case 2: Automatically pause video when elements leave view

Suppose we watch videos on YouTube and (for whatever reason) we want to scroll down to read the comments. I don't know how you are, but I usually don't pause the video before doing this, which means I miss some videos while browsing.

Wouldn't it be nice if the video will automatically pause when we're scrolling away from the video? It would be even better if the video resumes playing when it re-enters the field of view, so there is no need to click the play or pause button.

Intersection Observer can certainly do this.

Here is our video in HTML:

<video controls="" src="OSRO-animation.mp4"></video>

Here is how we pause and play videos during each crossover (i.e. entry):

 let video = document.querySelector('video');
let isPaused = false; /* flag for automatically pausing video*/
let observer = new IntersectionObserver((entries, observer) => { 
  entries.forEach(entry => {
    if(entry.intersectionRatio!=1 && !video.paused){
      video.pause(); isPaused = true;
    }
    else if(isPaused) {video.play(); isPaused=false}
  });
}, {threshold: 1});
observer.observe(video);

Before I show you how to pause and play the video during each cross (i.e. entry), I want to draw your attention to the threshold property of options .

The value of threshold is 1. root and rootMargin will take the default values. This is equivalent to saying, “Hey, let me know once the element is fully visible in the viewport.”

Once a cross occurs and a callback is triggered, we will pause or play the video according to the following logic:

I'm not calling unobserve for the video, so the observer keeps watching the video and pauses every time the video leaves view.

Use Case 3: View how much content has been viewed

This can be explained and implemented in a variety of ways based on your content and your preferred way to measure how much content has been viewed.

For a simple example, we will observe the last paragraph of each post in the list of posts on the page. Once the last paragraph of the article is fully visible, we will assume that the article has been read—just like we might say that seeing the last car of a train is equivalent to seeing the entire train.

This is a demo that shows two articles on the page, each containing multiple paragraphs of text.

Our simplified HTML looks like this:

<div></div>

<h2>Article 1</h2>
<p></p>

<h2>Article 2</h2>
<p></p>

let n=0; /* Total number of articles viewed*/
let count = document.querySelector('#count');
let observer = new IntersectionObserver((entries, observer) => { 
  entries.forEach(entry => {
    if(entry.isIntersecting){
      count.textContent= `articles fully viewed - ${ n}`; 
      observer.unobserve(entry.target);
    }
  });
}, {threshold: 1});

document.querySelectorAll('article > p:last-child').forEach(p => { observer.observe(p) });

During each crossover (i.e. the last paragraph of the article is fully visible), we increment a counter: n, which represents the total number of articles read. We then display that number above the article list.

Once we have calculated the crossover of the last paragraph, we don't need to observe it anymore, so we call unobserve on it.

Thank you for your participation!

This is the example in this article we will view together. You may have learned how to use it to observe elements and trigger events based on their intersection with the viewport.

That is, caution is required when making visual changes based on cross data obtained through observers. Of course, Intersection Observer is very convenient when recording cross-data. However, when it is used to make changes on the screen, we need to make sure the changes don't lag, which is a possibility because we basically make changes based on data retrieved asynchronously . This may take some time to load.

As we can see, each cross entry has an attribute set that conveys information about the cross. In this post, I did not cover all of these properties, so be sure to check them out.

The image is preserved in its original format. Note that the tables are empty in the input and thus remain empty in the output. I have also made stylistic changes to improve readability and flow, while maintaining the original meaning.

The above is the detailed content of A Few Functional Uses for Intersection Observer to Know When an Element is in View. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
CSS tutorial for creating loading spinners and animations CSS tutorial for creating loading spinners and animations Jul 07, 2025 am 12:07 AM

There are three ways to create a CSS loading rotator: 1. Use the basic rotator of borders to achieve simple animation through HTML and CSS; 2. Use a custom rotator of multiple points to achieve the jump effect through different delay times; 3. Add a rotator in the button and switch classes through JavaScript to display the loading status. Each approach emphasizes the importance of design details such as color, size, accessibility and performance optimization to enhance the user experience.

Addressing CSS Browser Compatibility issues and prefixes Addressing CSS Browser Compatibility issues and prefixes Jul 07, 2025 am 01:44 AM

To deal with CSS browser compatibility and prefix issues, you need to understand the differences in browser support and use vendor prefixes reasonably. 1. Understand common problems such as Flexbox and Grid support, position:sticky invalid, and animation performance is different; 2. Check CanIuse confirmation feature support status; 3. Correctly use -webkit-, -moz-, -ms-, -o- and other manufacturer prefixes; 4. It is recommended to use Autoprefixer to automatically add prefixes; 5. Install PostCSS and configure browserslist to specify the target browser; 6. Automatically handle compatibility during construction; 7. Modernizr detection features can be used for old projects; 8. No need to pursue consistency of all browsers,

Creating custom shapes with css clip-path Creating custom shapes with css clip-path Jul 09, 2025 am 01:29 AM

Use the clip-path attribute of CSS to crop elements into custom shapes, such as triangles, circular notches, polygons, etc., without relying on pictures or SVGs. Its advantages include: 1. Supports a variety of basic shapes such as circle, ellipse, polygon, etc.; 2. Responsive adjustment and adaptable to mobile terminals; 3. Easy to animation, and can be combined with hover or JavaScript to achieve dynamic effects; 4. It does not affect the layout flow, and only crops the display area. Common usages are such as circular clip-path:circle (50pxatcenter) and triangle clip-path:polygon (50%0%, 100 0%, 0 0%). Notice

What is the difference between display: inline, display: block, and display: inline-block? What is the difference between display: inline, display: block, and display: inline-block? Jul 11, 2025 am 03:25 AM

Themaindifferencesbetweendisplay:inline,block,andinline-blockinHTML/CSSarelayoutbehavior,spaceusage,andstylingcontrol.1.Inlineelementsflowwithtext,don’tstartonnewlines,ignorewidth/height,andonlyapplyhorizontalpadding/margins—idealforinlinetextstyling

Styling visited links differently with CSS Styling visited links differently with CSS Jul 11, 2025 am 03:26 AM

Setting the style of links you have visited can improve the user experience, especially in content-intensive websites to help users navigate better. 1. Use CSS's: visited pseudo-class to define the style of the visited link, such as color changes; 2. Note that the browser only allows modification of some attributes due to privacy restrictions; 3. The color selection should be coordinated with the overall style to avoid abruptness; 4. The mobile terminal may not display this effect, and it is recommended to combine it with other visual prompts such as icon auxiliary logos.

How to create responsive images using CSS? How to create responsive images using CSS? Jul 15, 2025 am 01:10 AM

To create responsive images using CSS, it can be mainly achieved through the following methods: 1. Use max-width:100% and height:auto to allow the image to adapt to the container width while maintaining the proportion; 2. Use HTML's srcset and sizes attributes to intelligently load the image sources adapted to different screens; 3. Use object-fit and object-position to control image cropping and focus display. Together, these methods ensure that the images are presented clearly and beautifully on different devices.

Demystifying CSS Units: px, em, rem, vw, vh comparisons Demystifying CSS Units: px, em, rem, vw, vh comparisons Jul 08, 2025 am 02:16 AM

The choice of CSS units depends on design requirements and responsive requirements. 1.px is used for fixed size, suitable for precise control but lack of elasticity; 2.em is a relative unit, which is easily caused by the influence of the parent element, while rem is more stable based on the root element and is suitable for global scaling; 3.vw/vh is based on the viewport size, suitable for responsive design, but attention should be paid to the performance under extreme screens; 4. When choosing, it should be determined based on whether responsive adjustments, element hierarchy relationships and viewport dependence. Reasonable use can improve layout flexibility and maintenance.

What are common CSS browser inconsistencies? What are common CSS browser inconsistencies? Jul 26, 2025 am 07:04 AM

Different browsers have differences in CSS parsing, resulting in inconsistent display effects, mainly including the default style difference, box model calculation method, Flexbox and Grid layout support level, and inconsistent behavior of certain CSS attributes. 1. The default style processing is inconsistent. The solution is to use CSSReset or Normalize.css to unify the initial style; 2. The box model calculation method of the old version of IE is different. It is recommended to use box-sizing:border-box in a unified manner; 3. Flexbox and Grid perform differently in edge cases or in old versions. More tests and use Autoprefixer; 4. Some CSS attribute behaviors are inconsistent. CanIuse must be consulted and downgraded.

See all articles