How to Play and Pause HTML5 Media Using JavaScript?

Estimated read time 1 min read

To play and pause an HTML5 media element such as an audio or video tag using JavaScript, you can use the play() and pause() methods on the element. Here’s an example:

const myMedia = document.getElementById('my-media-element');

function playMedia() {
  myMedia.play();
}

function pauseMedia() {
  myMedia.pause();
}

In this example, myMedia is a reference to the audio or video element on the page, which is obtained using the document.getElementById() method. The playMedia function plays the media, and the pauseMedia function pauses it.

You can bind these functions to buttons or other elements in the page to control the media playback. For example:

const playButton = document.getElementById('play-button');
const pauseButton = document.getElementById('pause-button');

playButton.addEventListener('click', playMedia);
pauseButton.addEventListener('click', pauseMedia);

In this example, the playButton and pauseButton elements are references to buttons in the page, and the addEventListener method is used to bind the playMedia and pauseMedia functions to the click events of those buttons.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply