Play and pause HTML5 video by pressing space key in JavaScript

A lot of online video players including YouTube have the video play and pause functionality by pressing the space key from the keyboard. We all are aware of this. Now, in this post, I am going to show you how to play and pause HTML5 video by pressing space key in JavaScript.

So you can think that like YouTube, you will also see the play and functionality with space key on your own HTML5 video. This post will show you the JavaScript code snippet that will do this task.

Before I am going to JavaScript code, first let us create our HTML5 video player. Below is the HTML code to create our HTML5 video player:

<video width="500" id="cspd_video" controls>
  <source src="sp.mp4" type="video/mp4">
</video>

Now we are going to take our video in a JavaScript variable. Below is the code that will do that:

var theVideo = document.getElementById("cspd_video");

After that, we are going to create our simple JavaScript function to play and pause our HTML5 video:

function playPause() { 
    if (theVideo.paused) {
            theVideo.play();
        }
    else  {
            theVideo.pause();
        }
} 

In the above code, we have created a function which will pause our HTML5 video if it is already playing. If the video is already in paused mode, it will play when we call the function. We have used the JavaScript if else statement to check if our video is playing or not.

 

Also, read:

 

Now we will use onkeydown properties which contains the switch case statement that will play and pause our HTML5 video depending on its status:

document.onkeydown = function(event) {
    switch (event.keyCode) {
       
       case 32:
            event.preventDefault();
            playPause();
          break;
       
    }
};

In the last code snippet, you can see that we are checking if the key pressed is the space key or not by its ID. each and every key available on the keyboard has its own key code which is called ASCII code. the ASCII code of the space key is 32.

In our switch case statement, if the key code is 32, it will call our playPause() function which we have just created.

 

Leave a Reply

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