Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to play/pause html5 video with spacebar

Tags:

html5-video

How do you pause an html5 video with the spacebar using e.key? There's something off about 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();
                    }
                }
            }
        });
like image 755
Matt Avatar asked Nov 17 '14 20:11

Matt


2 Answers

Here's 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();
  }
});
like image 106
Abhilash Shamsunder Avatar answered Nov 08 '22 23:11

Abhilash Shamsunder


Use e.preventDefault() to stop the scrolling of the web page to bottom.

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(); 
}
}
like image 43
nayancy Avatar answered Nov 08 '22 21:11

nayancy