search
  • Sign In
  • Sign Up
Password reset successful

Follow the proiects vou are interested in andi aet the latestnews about them taster

Table of Contents
core idea
HTML structure
CSS styles
JavaScript logic
Summary and best practices
Home Web Front-end HTML Tutorial Efficiently manage multi-video modal playback: a scalable JavaScript solution

Efficiently manage multi-video modal playback: a scalable JavaScript solution

Dec 11, 2025 pm 08:24 PM

Efficiently manage multi-video modal playback: a scalable JavaScript solution

This article details how to use a set of scalable JavaScript solutions to implement multiple videos on the page through a single modal box (`

`element) to manage playback. Through dynamic loading of video sources, unified event processing mechanism and playlist navigation function, redundant code of creating independent modal boxes for each video is avoided, which greatly improves the maintainability and user experience of the code.

In modern web development, it is a common requirement to display multiple video contents and provide a modal box playback experience. However, writing a separate set of JavaScript codes for each video to open the modal box, play the video, and close the modal box will lead to redundant code and difficulty in maintaining, especially when there are a large number of videos. This tutorial walks you through building an efficient, scalable solution that leverages a single modal and a dynamic content loading mechanism to manage the playback of all videos.

core idea

The core of this solution lies in "single modal box, dynamic content". Instead of creating a separate HTML modal structure for each video, we use a common modal element. When the user clicks the play button or link of a video, JavaScript will capture this event, dynamically update the src and poster attributes of the video player in the modal box based on the clicked video information, and then display the modal box and start playing. At the same time, we will also introduce a playlist navigation function to allow users to switch between different videos within the modal box.

HTML structure

In order to implement the above functions, we need to define a video playlist and a general modal box. Here we use the HTML5

element as the modal box, which provides native modal box behavior.

 <!-- Video playlist-->
<ol class="playlist">
  <a href="#" id="0"><b>40</b> Seconds</a>
  <a href="#" id="1"><b>11</b> Seconds</a>
  <a href="#" id="2"><b>08</b> Seconds</a>
</ol>

<!-- Universal video playback modal box -->
<dialog class="scroll">
  <form id="ui" method="dialog">
    <fieldset class="content">
      <legend>
        <input class="btn" type="submit" value="⨯"> <!-- Close button-->
      </legend>
      <video controls></video> <!-- Video player-->
      <fieldset class="control">
        <input id="prev" class="btn" type="button" value="⏮"> <!-- Previous video button-->
        <output id="counter"></output> <!-- Current video index display-->
        <input id="next" class="btn" type="button" value="⏭"> <!-- Next video button-->
      </fieldset>
    </fieldset>
  </form>
</dialog>

Structure description:

CSS styles

In order to make the modal and playlist have a good visual effect, we need some CSS styles. Below are sample styles that you can adapt to suit your design needs.

 *,
*::before,
*::after {
  box-sizing: border-box;
}

html {
  font: 300 5vmin/1 "Segoe UI"
}

body {
  overflow: scroll
}

.playlist a {
  display: list-item;
  position: relative;
  width: max-content;
  color: #18272F;
  text-decoration: none;
}

.playlist aa {
  margin-top: 0.5rem;
}

.playlist a::before {
  content: '';
  position: absolute;
  width: 100%;
  height: 0.1rem;
  border-radius: 4px;
  background-color: #18272F;
  bottom: 0;
  left: 0;
  transform-origin: right;
  transform: scaleX(0);
  transition: transform .3s ease-in-out;
}

.playlist a:hover::before {
  transform-origin: left;
  transform: scaleX(1);
}

.playlist ab {
  font-weight: 300;
  font-family: Consolas;
  font-size: 1.1rem;
}

dialog {
  padding: 0;
  border: 0;
  border-radius: 5px;
  background: transparent;
  box-shadow: 0 10px 6px -6px #777;
}

dialog::backdrop {
  background: rgba(50, 50, 50, 0.3);
}  

#ui {
  padding: 0;
  border: 1.5px solid #bbb;
  border-radius: 5px;
  background: #eee;
}

.btn {
  display: inline-flex;
  justify-content: center;
  align-items: center;
  padding: 0;
  border: 1px ridge #ddd;
  border-radius: 5px;
  font: inherit;
  font-size: 2rem;
  line-height: normal;
  background: transparent;
  cursor: pointer;  
  box-shadow: 0 6px 4px -4px #bbb;
}

.btn:hover { 
  box-shadow: 0 6px 8px -4px #999;
}

.btn:active {
  transform: scale(0.95);
}

.content {
  display: flex;
  flex-flow: column nowrap;
  justify-content: center;
  align-items: center;
  width: 100vh;
  padding: 0 0.5rem;
  border: 0;
  background: #eee;
}

.content legend {
  width: 100%;
}

.content legend .btn {
  float: right;
  padding-bottom: 0.45rem;
  line-height: 0;
  height: 1.5rem;
  margin: 0.25rem -0.25rem 0.25rem 0;
  color: #888;
}

.control {
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 0 0 0.25rem;
  padding: 0;
  border: 0;
}

#prev,
#next {
  width: 2rem;
  height: 2rem;
  padding: 0;
  border: 0;
  line-height: 1;
  background: #eee;
}

#counter {
  font-size: 1.15rem;
  font-family: Consolas;
  padding: 0 0.75rem;
}

video {
  width: 100%;
}

.scroll::-webkit-scrollbar {
  display: none;
}

.scroll {
  -ms-overflow-style: none;
  scrollbar-width: none;
}

JavaScript logic

JavaScript is the core of dynamic video playback and modal box interaction.

 //Define the index of the currently playing video let idx = 0;

// Get DOM element reference const list = document.querySelector(".playlist"); // Playlist const links = Array.from(list.querySelectorAll("a")); // All video links in the playlist // Video file path and file name array const path = "https://glpjt.s3.amazonaws.com/so/av/"; // Video file public path const files = ["vs8s3", "vs21s3", "vs2s3"]; // Video file name (excluding extension)

const vid = document.querySelector("video"); // Video player in the modal box const mod = document.querySelector("dialog"); // Modal box element const ui = document.forms.ui; // Form in the modal box const io = ui.elements; // All elements in the form const prv = io.prev; // Previous video button const nxt = io.next; // Next video button const cnt = io.counter; // Video counter display/**
 * playList function: load and play videos according to index * @param {number} index - the index of the video in the `files` array */
function playList(index) {
  idx = index; // Update the current video index let file = files[index]; // Get the file name let mp4 = path file ".mp4"; // Construct the full path of the MP4 video let png = path file ".png"; // Construct the full path of the PNG poster vid.src = mp4; // Set the video source vid.poster = png; // Set the video poster cnt.value = idx 1; // Update the counter display (starting from 1)
  vid.play(); // Automatically play video}

/**
 *Click event processing of modal boxes and forms* Click on the background of the modal box to close the modal box, click on the content of the modal box to prevent the event from bubbling*/
mod.onclick = e =&gt; {
  // If the modal box itself (rather than its internal content) is clicked, close the modal box if (e.target === mod) {
    e.currentTarget.close();
    vid.pause(); // Pause video}
};
ui.onclick = e =&gt; e.stopPropagation(); // Prevent click events inside the form from bubbling up to the modal box/**
 * Bind click events to each video link * Assign each link an id as its index in the playlist */
links.forEach((a, i) =&gt; {
  a.id = i; // Set the link's id as the index a.onclick = openModal; // Bind the click event handler });

/**
 * openModal function: open the modal box and load the corresponding video * @param {Event} e - click event object */
function openModal(e) {
  e.preventDefault(); // Prevent the default behavior of the link mod.showModal(); // Display the modal box // Call the playList function and pass in the id of the clicked link (converted to a number)
  playList( this.id); 
}

//Bind click events for the "Previous" and "Next" buttons prv.onclick = reverse;
nxt.onclick = forward;

/**
 *reverse function: play the previous video*/
function reverse() {
  idx--; // Decrease the index by one // If the index is less than 0, loop to the end of the list idx = idx  files.length - 1 ? 0 : idx; 
  playList(idx); // Load and play new video}

JavaScript logic description:

  1. Initialize variables :
    • idx: The index of the currently playing video, initially 0.
    • list, links: Get the playlist container and all video link elements.
    • path, files: Define the video file path and file name array. Each element in the files array corresponds to a video.
    • vid, mod, ui, io, prv, nxt, cnt: Get references to key DOM elements such as modal boxes, video players, navigation buttons, etc.
  2. playList(index) function :
    • This is the core function, responsible for loading and playing videos based on the index parameter passed in.
    • It will update the global idx variable and get the corresponding video file name from the files array according to index.
    • Construct complete MP4 video path and PNG poster path.
    • Assign these paths to the vid.src and vid.poster properties to achieve dynamic switching of video content.
    • Update cnt.value to display the current video serial number.
    • Call vid.play() to automatically play the video.
  3. Modal box interaction :
    • mod.onclick: When the modal box is clicked, check whether the click target is the modal box itself (i.e. the background). If so, call mod.close() to close the modal and pause the video.
    • ui.onclick: Prevent click events of form elements inside the modal box from bubbling to the background of the modal box to prevent accidental closing.
  4. Video link event binding :
    • links.forEach(): Iterate through all video links, for each link:
      • Set its id property to its index in the links array.
      • Bind the openModal function as a click event handler.
  5. openModal(e) function :
    • Fired when the user clicks on a video link in the playlist.
    • e.preventDefault() prevents the default jump behavior of the link.
    • mod.showModal() displays the modal box.
    • playList(this.id) calls the playList function, this.id gets the id of the clicked link (i.e. video index), and converts it to a numeric type.
  6. Playlist navigation (reverse, forward) :
    • prv.onclick = reverse; nxt.onclick = forward;: Bind corresponding event handling functions to the "Previous" and "Next" buttons.
    • The reverse() and forward() functions will increment or decrement idx, handle the out-of-bounds index situation (implement loop playback), and then call playList(idx) to load and play the new video.

Summary and best practices

Through the above method, we have implemented a highly scalable multi-video playback modal box solution.

Main advantages:

  • Concise code : Avoid a lot of repeated HTML and JavaScript code.
  • Easy to maintain : To add, delete or modify video content, you only need to modify the files array and playlist HTML.
  • User experience : Provides smooth video switching and modal box experience, and supports playlist navigation.
  • Utilize native features : Take full advantage of the native modal box behavior of the HTML5 element.

Notes and extensions:

  • Error handling : In actual applications, you may need to add an error handling mechanism, such as displaying a prompt message when the video source fails to load.
  • Performance optimization : For playlists containing a large number of videos, consider lazily loading video data instead of loading all video information at once.
  • Keyboard Navigation : The element usually comes with some keyboard accessibility, but you can enhance it further, such as switching videos via the keyboard arrow keys.
  • Custom data attributes : In addition to using id as an index, you can also use data-* attributes to store more video-related information, such as video title, description, etc., and read them in JavaScript.
  • Video preloading : The video preloading strategy can be adjusted according to needs, such as preloading the next video before the modal box opens to reduce the waiting time when switching.
  • CSS animation : You can add CSS transitions or animations to the opening and closing of the modal box to improve the visual effect.

By following these principles and practices, you can build a powerful and user-friendly multi-video playback experience.

The above is the detailed content of Efficiently manage multi-video modal playback: a scalable JavaScript solution. 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

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

ArtGPT

ArtGPT

AI image generator for creative art from text prompts.

Stock Market GPT

Stock Market GPT

AI powered investment research for smarter decisions

Popular tool

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)

How to correctly migrate jQuery's drag and drop events to native JavaScript How to correctly migrate jQuery's drag and drop events to native JavaScript Mar 06, 2026 pm 05:15 PM

This article explains in detail the key pitfalls when migrating jQuery drag-and-drop logic (such as dragover/dragleave) to Vanilla JS - especially the problem of misuse of e.originalEvent causing dataTransfer failure, and provides directly runnable fixes and best practices.

How to make the images in a div fill with no margins while retaining the inner margins of the text How to make the images in a div fill with no margins while retaining the inner margins of the text Mar 07, 2026 pm 10:54 PM

This article explains how to keep the overall padding of the container so that the internal images are displayed close to the edge of the container, while the text content still maintains normal padding - the core is to separate the style scope and achieve precise layout through positioning and box model control.

Solve the problem of unexpected offset of Flex container due to the font size change of the first child element Solve the problem of unexpected offset of Flex container due to the font size change of the first child element Mar 09, 2026 pm 08:15 PM

When the first child element of a Flex container dynamically adjusts the font-size, the container will be vertically offset along the inline baseline; while a normal block-level container will change in height due to the linkage between line height and font measurement. The root cause lies in the baseline alignment mechanism of the Flex container. By default, the baseline of the first child is the container baseline. This can be completely solved through vertical-align: top or explicit baseline control.

A complete guide to using the keyboard to control the smooth movement of HTML elements A complete guide to using the keyboard to control the smooth movement of HTML elements Mar 13, 2026 pm 10:18 PM

This article explains in detail why transform: translate() combined with the keydown event cannot move elements, and provides a reliable solution based on CSS positioning and JavaScript, covering absolute positioning settings, coordinate update logic, code robustness optimization, and common pitfalls.

Chart.js complete implementation solution for dynamically switching chart types (line chart, bar chart, pie chart) Chart.js complete implementation solution for dynamically switching chart types (line chart, bar chart, pie chart) Mar 12, 2026 pm 08:51 PM

This article explains in detail how to safely and reliably dynamically switch chart types (line/bar/pie) in Chart.js, and solve the problem of Cannot read properties of undefined errors caused by mismatched data structures and rendering exceptions after type switching. The core lies in destroying old instances, deep copying configurations, and accurately rebuilding data structures by type.

How to dynamically pass HTML form data to analytics.track() method How to dynamically pass HTML form data to analytics.track() method Mar 13, 2026 pm 10:57 PM

This article explains in detail how to safely and efficiently extract user input from HTML forms and structure it into JavaScript objects as attribute parameters of analytics.track() to avoid hard coding and syntax errors and support flexible expansion.

How to properly override default styles and implement custom CSS layouts in Divi theme builder How to properly override default styles and implement custom CSS layouts in Divi theme builder Mar 14, 2026 am 12:00 AM

This article explains in detail the root cause of style failure when applying custom CSS in the WordPress Divi theme builder. It provides practical solutions for improving selector specificity, accurately positioning elements, and rational use of !important, as well as debugging tips and code optimization examples.

How to optimize Lighthouse image scoring while maintaining high image quality How to optimize Lighthouse image scoring while maintaining high image quality Mar 11, 2026 pm 09:39 PM

This article explores why providing 2x images to high DPR devices may lower Lighthouse performance scores, and provides practical solutions to balance visual quality and real performance: including proper srcset configuration, image compression strategies, modern format selection, and load priority control.

Related articles