Have you ever wondered how the automatic video play on scroll feature works on Tiktok.com and YouTube shorts when using a mobile device?

My goal with React JS is to develop a website similar to Tiktok, where the video below will automatically play with sound as the user scrolls down.

I attempted to set this up using

window.addEventListener("scroll",...)
, but after looking into it further, I found that this method may not work because scrolling isn't considered a "valid user input" for playing videos on mobile devices.

Further research led me to believe that playing and pausing all videos from an initial user input click could be the solution. However, I am still figuring out how to implement this play/pause functionality for all videos from a single input.

My question is, how do websites like tiktok.com and youtube shorts manage to autoplay videos with sound while users are scrolling? What techniques are they using to accomplish this?

Answer №1

There are numerous approaches to accomplish this task.

Personally, I prefer utilizing the Intersection Observer API.

This API enables you to execute a callback function when an element enters the viewport.

According to the documentation, here are some common use cases:

  • Lazy-loading images or content as a user scrolls through a webpage.
  • Implementing endless scrolling websites where content loads continuously as the user scrolls.
  • Monitoring ad visibility for revenue calculations.
  • Determining whether to initiate tasks or animations based on user visibility.

The Intersection Observer API triggers the callback when either of these conditions is met:

  • An element intersects with the viewport or a specified root element.
  • The observer starts watching a target element for the first time.
let options = {
  root: document.querySelector('#scrollArea'),
  rootMargin: '0px',
  threshold: 1.0
}

let observer = new IntersectionObserver(callback, options);

// Alternatively

var intersectionObserver = new IntersectionObserver(function(entries) {
  if (entries[0].intersectionRatio <= 0) return;

  loadItems(10);
  console.log('Loaded new items');
});

intersectionObserver.observe(document.querySelector('.scrollerFooter'));

I have developed a small npm package specifically for lazy loading functionality.

https://www.npmjs.com/package/dyno-img-react

This package displays a low-resolution image until the user reaches the specified intersection area, at which point it fetches and displays the high-quality image before removing the observer.

If you are working with React Native, I recommend checking out this library:

react-native-intersection-observer

You can find the implementation details in the following code snippet:

https://github.com/zhbhun/react-native-intersection-observer/blob/master/src/IntersectionObserver.ts

This library utilizes the onLayout event internally for management.

import { IOScrollView, InView } from 'react-native-intersection-observer'

const Component = () => (
  <IOScrollView>
    <InView onChange={(inView: boolean) => console.log('Inview:', inView)}>
      <Text>Plain children are always rendered. Use onChange to monitor state.</Text>
    </InView>
  </IOScrollView>  
)

export default Component

Answer №2

Take a look at this informative guide regarding the availability of autoplay:

  • Audio must be muted or set to 0 volume
  • User interaction with the site is required (such as clicking, tapping, or pressing keys)
  • Websites may be whitelisted for autoplay, either automatically based on user media engagement or manually through preferences and UI features
  • Autoplay feature policy can grant support for autoplay in certain contexts

If these conditions are not met, playback will likely be blocked. The specifics of blocking scenarios and whitelisting processes vary between browsers, but the provided guidelines are generally applicable.

To enable the autoplay feature, users may need to adjust their settings. Here's an example feature policy header you can use:

Feature-Policy: autoplay

When embedding content in iframes, ensure autoplay is allowed:

<iframe src="mediaplayer.html"
  allow="autoplay 'src'">
</iframe>

Although some browsers block autoplay with sound due to user annoyance, configurations can be adjusted to enable sound playback.

For comprehensive information on autoplay, refer to the guide. Additionally, check out this tool for permitted autoplay devices and read about autoplay policy changes.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Receive the outcome once the form is submitted

Can someone provide quick assistance? I am looking to allow users to upload a CSV file for me to parse and analyze. Once the processing is done, I need to display the results back to the users. While uploading the file, I also need to ensure that the file ...

Creating an animated time-based scrollable bar chart in javascript

As someone who is new to JavaScript and charting, I am seeking assistance with a specific task. Despite browsing various JavaScript charting libraries and examples, none seem to address my issue: My goal is to generate dynamic stacked bar charts, as depic ...

Perform an additional HTTP request and utilize the response within the existing Observable

In my Angular 2 project, I am utilizing the http component to make API calls. The specific REST API I want to access returns a maximum of 100 Elements in one request. If more items exist, a hasMore flag is included in the response. To retrieve additional ...

The button in discord.js is unresponsive and does not seem to be

Hey there! I've written some code for a specific function. However, when I run the command, only the text is displayed in my channel and not the buttons. I'm puzzled as to why this is happening because I don't see any errors. Can anyone help ...

Make sure to select only one radio button from the form, rather than selecting all of them

This form was designed to create a dynamic react page where options are selected using radio buttons. Currently, I am able to select all radio buttons displayed, but I want to limit it to selecting only one from the generated list. <Card className={cl ...

Techniques for accessing the most recent input values within a loop

Here is the HTML code snippet: <div v-for="item in my_items"> <div> <input type="text" :value=item.name /> </div> <div> <button @click="edit(item.id, item.name)">Edit ...

Utilizing conditional statements for confirming purchased orders with a pop-up confirmation box

function purchaseClicked() { var orders = prompt("Are you sure you want to buy these Items?"); if (orders != null) { alert('Please try selecting your items again!') } else { alert('Thank you for shopping ...

Conundrum regarding setting up configuration for express-session middleware in Express version 4.x

Hello, I'm currently diving into node.js and still trying to grasp the concept of configurations in sessions. Below is a basic example of how sessions are used in my app: app.js var express = require('express'); var bodyParser = require(&a ...

Executing an xajax/ javascript function simultaneously

Is there a way to simultaneously execute the same function? Here is an example: function convert_points() { show_loading(); xajax_ConvertPoints(); xajax_GetRegularGamingCards(); } When xajax_ConvertPoints is called, there seems to be a mill ...

Which one should you begin with: AngularJS or Angular 2?

Interested in learning Angular and curious about the differences between Angular, AngularJS, and Angular 2. Should I focus on educating myself on Angular or go straight to Angular 2, considering it's now in beta version? Is there a significant differ ...

Experience the benefits of React Lazy for efficient component loading as it strategically delays their load with the added suspense

I want to explore the potential of utilizing Suspense and Lazy. To achieve this, I have been contemplating on deferring or delaying the loading of a component for a specific duration. However, my attempts thus far have been unsuccessful. To elaborate, wha ...

Guide to modifying text color in a disabled Material-UI TextField | Material-UI version 5

How can I change the font color of a disabled MUI TextField to black for better visibility? See below for the code snippet: <TextField fullWidth variant="standard" size="small" id="id" name=&quo ...

Encountering Babel issues while incorporating npm package into React Native project

Currently, I am developing a React Native application. In an attempt to enhance my application, I decided to incorporate the npm package available at this link: https://github.com/MagicTheGathering/mtg-sdk-javascript/ Despite trying various import statem ...

What steps do I need to take in order to generate a legitimate link annotation within Adobe Acrobat by utilizing Acrobat

Seeking guidance on how to embed an Acrobat Javascript within Adobe Acrobat in order to generate a link annotation. The current method involves using the "addLink" function within the document object, which triggers a Javascript action upon clicking the li ...

Error message from BitBucket pipeline indicates that the npm command was not found

Upon deploying code to my server via the Bit Bucket scp pipeline, I encountered an issue with another pipeline meant to install node modules and start the node server. The pipeline returned a failed status and displayed the following error: ./server-run.s ...

Adjusting the appearance of Material-ui table within the row.getRowProps() function

I am currently working on a React application that utilizes Material-UI enhanced table, which is based on react-table. I have been trying to customize the styling of their rows. According to the documentation (https://material-ui.com/api/table-row/), it s ...

Tips on how to direct the attention to a text box within a unique dialog, ensuring that the blinking cursor highlights the input area

Is there a way to set autofocus on a textbox when opening a custom dialog box? I've tried using the autofocus attribute for the input field, but it doesn't seem to work for me. Can anyone provide guidance on how to achieve autofocus for a textfie ...

Key Enhancements for Functional Stateless Components

How can I accurately assign a key in a functional component, specifically using the 'key' keyword instead of just a general index? I am attempting to use Map in a functional component to generate a list of another element. However, when I try to ...

Transmitting data with PHP forms

I'm in a bind. Need to send form values to an Email address. Here's the HTML code: <form class="form" id="form1"> <p class="name"> <input name="name" type="text" class="valida ...

I am unable to loop through and display the buttons

I have a button object within my component that I want to iterate through and display all the buttons {0: {…}, 1: {…}, isActive: true} 0: {key: ':R2m:', text: 'Trading', isActive: true} 1: {key: ':R2mH1:', text: 'Ba ...