How to play / pause html5 video using spacebar
How to pause html5 video with spacebar using e.key? There is something wrong with the logic ...
<div class=modal-video id="v-5417">
<div class=video-player>
<video id=v-5417-tape preload="none">
<source type="video/mp4" src="videos/anthem-od47.mp4">
<source type="video/webm" src="videos/anthem-od47.webm">
</video>
<div class="close-modal fade-control"></div>
</div>
</div>
Js
$( document ).on( 'keydown', function ( e ) {
if ( e.keyCode === 32 ) {
if (video.paused == true) {
// Play the video
video.play();
}else{
if(video.play == true){
video.pause();
}
}
}
});
+4
source to share
4 answers
Here are the changes to your JavaScript:
$(window).keypress(function(e) { var video = document.getElementById("vid"); if (e.which == 32) { if (video.paused) video.play(); else video.pause(); } });
+7
source to share
var videoPlayer = document.getElementById('Video1')
$(window).keypress(function(e) {
if (e.keyCode == 0 || e.keyCode == 32) {
if (videoPlayer.paused == false) {
videoPlayer.pause();
videoPlayer.firstChild.nodeValue = 'Play';
} else {
videoPlayer.play();
videoPlayer.firstChild.nodeValue = 'Pause';
}
}
});
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script src="/website/js/playPause.js></script>
</head>
<body>
<center>
<h1>Video</h1>
<video id="Video1" autoplay="yes">
<source src="videoName.mp4" type="video/mp4" />
</video>
</center>
</body>
</html>
0
source to share
Here you go, this should work.
// Press spacebar to Play/Pause.
var body = $( 'body' );
body.keypress( function ( e ) {
if ( e.which == 32 ) {
// Stop the jerk.
e.preventDefault();
// If video is paused.
if ( theVideo.get(0).paused == true ) {
theVideo.get(0).play();
} else {
theVideo.get(0).pause();
}
}
}); // End keypress().
0
source to share
Use e.preventDefault()
to stop scrolling down a web page.
var vid=document.getElementById('your_video_id_goes_here');
document.body.onkeypress = function(e){
if(e.which == 32){
// stops default behaviour of space bar. Stop page scrolling down
e.preventDefault();
play_pause_video
}
}
function play_pause_video() {
if (vid.paused)
{
vid.play();
}
else
{
vid.pause();
}
}
0
source to share