Search code examples
htmlhtml5-video

How to play/pause html5 video with spacebar


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

Solution

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