Techiio-author
Started by Marrine MorelSep 15, 2021

Open
How to play next video by pressing spacebar in html and JS?

2 VIEWES 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 2 VIEWES SHARE

I want to play a video by pressing the spacebar then the video got paused and a black screen shows and when I again press the space bar net video gets played and the cycle repeat.

1 Replies

Techiio-commentatorPOULAMI SARKAR replied a month ago0 likes0 dislikes

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();
}
}

We have created a function that will pause our HTML5 video if it is already playing in the above code. If the video is already in paused mode, it will play when calling the function. We have used the JavaScript if-else statement to check if our video is playing.

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.

You must be Logged in to reply
Trending Technologies
15
Software40
DevOps47
Frontend Development24
Backend Development20
Server Administration17
Linux Administration26
Data Center24
Sentry24
Terraform23
Ansible83
Docker70
Penetration Testing16
Kubernetes21
NGINX20
JenkinsX17
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance