Playing Video using JavaScript

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone

To play a video clip on a web page, you need to use the <video> element in HTML5 to define the video screen size and the <source> element to refer to the source of the video file.  Besides, you have to give an id to the video source so that the Javascript function can refer to it.

For the JavaScript, we use the document.getElementById to refer to the video clip. To play the video clip, we use the play method and to pause the video clip, we use the pause method.

The full script is as follows:

<!DOCTYPE html> 
<html> 
<body> 
<button onclick="playVideo()" type="button">Play</button>
<button onclick="pauseVideo()" type="button">Pause</button><br> 
<video id="myVid" width="400" height="200">
 <source src="beach.mp4" type="video/mp4">
  Sorry, your browser does not support HTML5 video.
</video>
<script> 
var myVideo = document.getElementById("myVid");
function playVideo() { 
 myVideo.play(); 
} 
function pauseVideo() { 
 myVideo.pause(); 
} 
</script> 
</body> 
</html>

Click Play Video to view the output.

Share on FacebookShare on Google+Tweet about this on TwitterShare on LinkedInEmail this to someone