HTML Video play() Method: Starting Video Playback

The HTML Video play() method initiates the playback of a video element in a web page. This method is essential for controlling the video’s state, allowing users to start or resume video playback via JavaScript. In this guide, we will explore the syntax, usage, and practical examples of the play() method, providing you with a comprehensive understanding of how to effectively manage video playback in your web applications.

What is the play() Method?

The play() method is a function available on HTML <video> elements that, when called, starts or resumes the video’s playback. It is a fundamental part of the video control interface, enabling programmatic control over the video’s play state.

Purpose of the play() Method

The primary purpose of the play() method is to:

  • Start video playback when the video is paused or stopped.
  • Resume video playback from a paused state.
  • Allow developers to create custom video controls.
  • Enable dynamic video experiences based on user interactions or other events.

Syntax of the play() Method

The play() method does not accept any parameters and returns a Promise that resolves when the video starts playing.

let promise = videoElement.play();

if (promise !== undefined) {
  promise
    .then(() => {
      // Autoplay started!
    })
    .catch((error) => {
      // Autoplay was prevented.
      console.error("Autoplay prevented:", error);
    });
}

Return Value

  • Promise: A Promise that resolves when the video starts playing successfully. If autoplay is prevented by the browser, the Promise will reject with an error.

Practical Examples of the play() Method

Let’s explore practical examples of how to use the play() method effectively.

Basic Example: Starting Video Playback with a Button

This example demonstrates how to start video playback when a button is clicked.

<video
  id="myVideo1"
  width="320"
  height="176"
  controls
  muted
  loop
  style="border: 1px solid black;"
>
  <source
    src="https://www.w3schools.com/html/mov_bbb.mp4"
    type="video/mp4"
  />
  Your browser does not support HTML5 video.
</video>

<button id="playButton1">Play Video</button>

<script>
  const video1 = document.getElementById("myVideo1");
  const playButton1 = document.getElementById("playButton1");

  playButton1.addEventListener("click", function () {
    video1.play();
  });
</script>

In this example, clicking the “Play Video” button triggers the play() method, starting the video playback.

Starting Video Playback on Mouse Over

This example shows how to start video playback when the mouse hovers over the video element.

<video
  id="myVideo2"
  width="320"
  height="176"
  muted
  loop
  style="border: 1px solid black;"
>
  <source
    src="https://www.w3schools.com/html/mov_bbb.mp4"
    type="video/mp4"
  />
  Your browser does not support HTML5 video.
</video>

<script>
  const video2 = document.getElementById("myVideo2");

  video2.addEventListener("mouseover", function () {
    video2.play();
  });
</script>

Here, the video starts playing automatically when the mouse pointer is moved over it.

Dynamically Handling Autoplay Prevention

This example demonstrates how to handle scenarios where autoplay is prevented by the browser, providing a user-friendly message.

<video
  id="myVideo3"
  width="320"
  height="176"
  muted
  loop
  style="border: 1px solid black;"
>
  <source
    src="https://www.w3schools.com/html/mov_bbb.mp4"
    type="video/mp4"
  />
  Your browser does not support HTML5 video.
</video>

<button id="playButton3">Play Video</button>

<script>
  const video3 = document.getElementById("myVideo3");
  const playButton3 = document.getElementById("playButton3");

  playButton3.addEventListener("click", function () {
    let playPromise = video3.play();

    if (playPromise !== undefined) {
      playPromise
        .then(() => {
          // Autoplay started!
        })
        .catch((error) => {
          // Autoplay was prevented.
          console.error("Autoplay prevented:", error);
          alert(
            "Autoplay was prevented by your browser. Please ensure autoplay is enabled for this site."
          );
        });
    }
  });
</script>

In this example, the Promise returned by play() is used to handle potential autoplay prevention, informing the user if necessary.

Toggle Play/Pause Functionality

This example demonstrates how to toggle between play and pause states with a single button.

<video
  id="myVideo4"
  width="320"
  height="176"
  controls
  muted
  loop
  style="border: 1px solid black;"
>
  <source
    src="https://www.w3schools.com/html/mov_bbb.mp4"
    type="video/mp4"
  />
  Your browser does not support HTML5 video.
</video>

<button id="toggleButton4">Play</button>

<script>
  const video4 = document.getElementById("myVideo4");
  const toggleButton4 = document.getElementById("toggleButton4");

  toggleButton4.addEventListener("click", function () {
    if (video4.paused) {
      video4.play();
      toggleButton4.textContent = "Pause";
    } else {
      video4.pause();
      toggleButton4.textContent = "Play";
    }
  });
</script>

Here, the button toggles between “Play” and “Pause” based on the video’s current state, providing a seamless user experience.

Starting Video Playback on Scroll into View

This example shows how to start video playback when the video element scrolls into the viewport.

<style>
  #scrollContainer5 {
    height: 500px;
    overflow: auto;
    border: 1px solid black;
    margin-bottom: 20px;
  }

  #myVideoContainer5 {
    margin-top: 600px;
  }
</style>

<div id="scrollContainer5">
  <div id="myVideoContainer5">
    <video
      id="myVideo5"
      width="320"
      height="176"
      muted
      loop
      style="border: 1px solid black;"
    >
      <source
        src="https://www.w3schools.com/html/mov_bbb.mp4"
        type="video/mp4"
      />
      Your browser does not support HTML5 video.
    </video>
  </div>
</div>

<script>
  const video5 = document.getElementById("myVideo5");
  const scrollContainer5 = document.getElementById("scrollContainer5");

  function isInViewport(element) {
    const rect = element.getBoundingClientRect();
    return (
      rect.top >= 0 &&
      rect.left >= 0 &&
      rect.bottom <=
        (window.innerHeight || document.documentElement.clientHeight) &&
      rect.right <= (window.innerWidth || document.documentElement.clientWidth)
    );
  }

  scrollContainer5.addEventListener("scroll", function () {
    if (isInViewport(video5)) {
      video5.play();
    } else {
      video5.pause();
    }
  });
</script>

In this example, the video starts playing when it scrolls into the viewport and pauses when it scrolls out, enhancing user engagement.

Browser Support

The play() method is widely supported across modern web browsers, ensuring consistent behavior across different platforms.

| Browser | Version | Support |
| ————— | ——- | ——- |
| Chrome | Yes | Yes |
| Firefox | Yes | Yes |
| Safari | Yes | Yes |
| Edge | Yes | Yes |
| Opera | Yes | Yes |
| Internet Explorer | 9+ | Yes |

Note: While the play() method itself is well-supported, autoplay policies may vary across browsers. Always handle potential autoplay prevention gracefully. ⚠️

Tips and Best Practices

  • Handle Autoplay Prevention: Always handle the Promise returned by play() to catch and respond to autoplay prevention.
  • User Interaction: Start video playback based on user interactions to comply with browser autoplay policies.
  • Provide Controls: Ensure users have controls to play, pause, and adjust the video as needed.
  • Optimize Performance: Load video resources efficiently to provide a smooth playback experience.
  • Accessibility: Ensure video content is accessible to all users, including those with disabilities.

Conclusion

The HTML Video play() method is a fundamental tool for controlling video playback in web applications. By understanding its syntax, usage, and practical applications, you can create dynamic and engaging video experiences for your users. From basic play buttons to advanced scroll-based playback, the play() method provides the flexibility and control needed to manage video content effectively.