How do I play an HTML5 video in a webpage with the press of a single key (eg. pressing the 'R' key) instead of using the mouse? Can I somehow use javascript to do this?
Yes, It can be done. Following is the code which should work.
<script type="text/javascript">
function myKeyPress(e){
var keynum;
if(window.event) { // IE
keynum = e.keyCode;
} else if(e.which){ // Netscape/Firefox/Opera
keynum = e.which;
}
if(keynum == 82){ // 82 is key code for r.
var samplevideo = document.getElementById('samplevideo');
samplevideo.play();
}
}
</script>
Here is the code,
<!DOCTYPE html>
<html>
<head>
<script src="//code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<body>
<video width="400" controls id="videoId">
<source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
<source src="http://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
Your browser does not support HTML5 video.
</video>
</body>
<script type="text/javascript">
$(document).keydown(function(e) {
if (e.keyCode == 82 ) {
alert("You have Pressed R , lets play the video");
document.getElementById('videoId').play();
}
});
</script>
</html>
i have also created a fiddle .
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.