Categories
JavaScript Answers

How to show or hide controls programmatically in a HTML5 video with JavaScript?

Spread the love

Sometimes, we want to show or hide controls programmatically in a HTML5 video with JavaScript.

In this article, we’ll look at how to show or hide controls programmatically in a HTML5 video with JavaScript.

How to show or hide controls programmatically in a HTML5 video with JavaScript?

To show or hide controls programmatically in a HTML5 video with JavaScript, we can add or remove the controls attribute programmatically.

For instance, we write

<video id="myvideo">
  <source src="path/to/movie.mp4" />
</video>

<p onclick="toggleControls();">Toggle</p>

to add the video and p element.

Then we write

const video = document.getElementById("myvideo");

function toggleControls() {
  if (video.hasAttribute("controls")) {
    video.removeAttribute("controls");
  } else {
    video.setAttribute("controls", "controls");
  }
}

to select the video element with getElementById.

When we click on the p element, toggleControls is called.

In it, we check if the controls attribute is added to the video element with hasAttribute.

If it is, we call removeAttribute to remove it.

Otherwise, we call setAttribute to add it.

Conclusion

To show or hide controls programmatically in a HTML5 video with JavaScript, we can add or remove the controls attribute programmatically.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *