preface

In my spare time, I studied javascript’s Intersection Observer API and found that it has a lot of application scenarios, such as lazy loading of images or content, parallax animation, etc. In the previous article, the author also introduced three types of Observer usage in detail, including position monitor, DOM change monitor and window change monitor. They have many application scenarios, so it is necessary to understand them. If you are interested, you can read this article and learn about it (some very interesting javascript points summarized).

There is a very common example, usually like to watch a short video of friends might notice that when we browse a video headlines, scrolling video list, when a video scroll to phone a certain position (generally may be regarded as the center), the video will automatically play, when removed from the designated area after the video will automatically shut down and play in the designated area of the next video, As follows:

The author’s first idea is to monitor the scrolling position to judge whether a video element reaches the specified area. However, this method needs to deal with many conditions, such as boundary condition judgment, scrolling direction judgment, etc., and frequent triggering will also lead to performance problems.

The Intersection Observer API is used to monitor changes in the position of elements under a given root element and perform some custom operations:

Intersection Observer The author will use the API provided by Intersection Observer to automatically play videos while rolling. If you are not familiar with the API, you can use several interesting javascript points to summarize

The author will use the popular Dplayer, which can easily operate the display of videos and achieve good exclusive playback control, and supports bullet screen.

The body of the

The Intersection Observer API is used to implement the Intersection Observer API. The general idea is as follows:

Intersection Observer
rootMargin
thresholds
Dplayer
mutex
rootMargin

rootMargin
top
right
bottom
left
rootMargin

With these ideas in mind, we can achieve the effect shown in the ABOVE GIF. The author will use React to implement. Before implementing react, we will prepare several video materials and then implement the basic framework of the list:

import React, { useEffect, useState } from 'react'
import VideoItem from 'components/VideoItem'
import styles from './videoList.less'

const data = [
    // List of videos
]

function VideoList(props) {
  useEffect((a)= > {
    let observerVideo = new IntersectionObserver(
        (entries, observer) = > {
            entries.forEach(entry= > {
                // When moving into the specified area, play the video
                if(entry.intersectionRatio === 1) {
                    // Some operations
                    return
                }
                // Stop listening
                // observer.unobserve(entry.target);
              });
            }, 
            {
              root: document.getElementById('scrollView'),
              rootMargin: '-180px 0px -180px 0px'.threshold: 1});document.querySelectorAll('.video-item').forEach(video= > { observerVideo.observe(video) });
  }, [])
  return <div className={styles.videoWrap}>
    <div className={styles.list} id="scrollView">
        {
            data.map(item => {
                return <VideoItem src={item} groupName="video-item" key={item} />})}</div>
  </div>
}

export default VideoList
Copy the code

The VideoItem component of the above code will be covered later. Now, the problem is that we have listened to the video element that needs to be played automatically, but how do we tell the VideoItem component to play? The author’s implementation idea here is to add a custom attribute to VideoItem. The value of this attribute is the SRC of the current video. When we listen to a video element that needs to be played, we can get the custom attribute set before and pass it to VideoItem as prop. When the VideoItem component listens for the prop change and equals its own SRC, the video is played. The code is as follows:

// VideoItem.js
import React, { useRef, useEffect } from 'react';
import DPlayer from 'dplayer';

export default (props) => {
    let videoRef = useRef(null)
    let dpRef = useRef(null)
    let { src, groupName, curPlaySrc } = props
    useEffect((a)= > {
        dpRef.current = new DPlayer({
            container: videoRef.current,
            screenshot: true.video: {
                url: src,
                thumbnails: 'logo.png'
            },
            logo: 'logo.png'
        });
    }, [])

    useEffect((a)= > {
        // Play the video when the url of the video that should be played is equal to the SRC of the current video component
        if(curPlaySrc === src) {
            dpRef.current.play()
        }
    }, [curPlaySrc])
    return <div data-src={src}>
        <div ref={videoRef}></div>
    </div>
}
Copy the code

Now the code of the video list page is as follows:

// ...
function VideoList(props) {
  const [curPlaySrc, setCurPlaySrc] = useState(' ')
  useEffect((a)= > {
    let observerVideo = new IntersectionObserver(
        (entries, observer) = > {
            entries.forEach(entry= > {
                // When moving into the specified area, play the video
                if(entry.intersectionRatio === 1) {
                    // Sets the url of the current video to play
                    setCurPlaySrc(entry.target.dataset.src)
                    return}}); }, {root: document.getElementById('scrollView'),
              rootMargin: '-180px 0px -180px 0px'.threshold: 1});document.querySelectorAll('.video-item').forEach(video= > { observerVideo.observe(video) });
  }, [])
  return <div className={styles.videoWrap}>
    <div className={styles.list} id="scrollView">
        {
            data.map(item => {
                return <VideoItem src={item} groupName="video-item" key={item} curPlaySrc={curPlaySrc} />})}</div>
  </div>
}
Copy the code

The above steps complete the function of automatically playing the video based on the specified area. The effect is as follows:

Experience the address

  • The video automatically plays the demo
  • Imitation wechat circle of friends dynamic demo

The last

If you want to learn more H5 games, Webpack, Node, gulp, CSS3, javascript, nodeJS, Canvas data visualization and other front-end knowledge and actual combat, welcome to join our technology group in the official number “Interesting Talk Front-end” to learn and discuss together, explore the frontier of the front-end together.

More recommended

  • React/Vue to develop a friend app for programmers
  • React builds a common form management configuration platform
  • Summary of several common sorting algorithms and search algorithms necessary for programmers
  • A couple of very interesting javascript points to summarize
  • The front step from zero to one realizes unidirectional & bidirectional lists
  • Micro front-end architecture and my front-end technology inventory
  • Develop your own graph bed application using nodeJs
  • Implementing a CMS full stack project from 0 to 1 based on nodeJS (part 1)
  • Implementing a CMS full stack project from 0 to 1 based on nodeJS
  • Vue and React
  • Write a mock data server using nodeJS in 5 minutes
  • From zero to one teaches you to develop a component library based on VUE
  • Build front-end team component systems from 0 to 1
  • 8 frequently used custom hooks by hand in 10 minutes
  • 15 minutes on javascript design patterns that front-end engineers must know (with detailed mind maps and source code)
  • Implementing pluggable cross-domain chatbot using postMessage