How to Play and pause HTML5 video by space bar key press in JavaScript?


Lots of online video players, Like YouTube have the video play and pause option by pressing the space bar key from the keyboard. We all know this. Now, in this tutorial, We are going to show you how to play and pause HTML5 video by space bar key in JavaScript.

So we can think like that, YouTube, you will also see the play and pause functionality with space bar key press on your own HTML5 video. This article will show you the JavaScript code sample that will do this task.

Before, We are going to JavaScript code snippet, first let us generate our HTML5 video player. Given below is the HTML code to generate our HTML5 video player:

HTML Video Player :

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

After that we are going to get our video in a JavaScript variable by using the id.

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

Now, we are going to generate our JavaScript function to play and pause our HTML5 video:

function playPause() { 
    if (theVideo.paused) {
    else  {

In the upper given code, we have generated a function, This will pause our HTML5 video if it is playing already. If the video is already in stop/pause mode, it will play the video when we call the function by pressing key. We have to used the JavaScript if and else statement to check if video is playing or not.

Now,after that,you will see to use onkeydown properties which hold the switch case statement which will play and pause our HTML5 video depending on its status:

document.onkeydown = function(event) {
    switch (event.keyCode) {
       case 32:

Have Fun!

Like it? Share with your friends!