Home > Enterprise >  How to implement "press space to pause html5 video" except when input is focused? (Jquery)
How to implement "press space to pause html5 video" except when input is focused? (Jquery)

Time:09-24

I'm looking to implement a space-to-pause system for a HTML5 video on my site via jquery, but what I find is that when I've clicked on an input on the same page, adding a space to the text input doesn't work. It just keeps playing/pausing the video.

What I'm looking to do is some kind of if statement that says "if input is not focused, press space to pause video", but also something to repeatedly check this condition so it doesn't happen just once.

I was almost successful using setInterval to do this but jquery's timing is completely imprecise and just leads to the video only pausing sometimes.

Current space-to-pause code is as follows.

    $(window).keypress(function(e) {
  var video = document.getElementById("vid");
  if (e.which == 32) {
    if (video.paused)
      video.play();
    else
      video.pause();
  }
});

Thanks for any help.

CodePudding user response:

I'd suggest checking the target of your click event and working based on that! Something like this should work

$(window).keypress(function(e) {
  const video = document.getElementById("vid");

  // check if keypress event originates from an input and if so; NOOP
  const nodeName = e.target.nodeName;
  if (nodeName && nodeName.toUpperCase() === "INPUT") { return; }

  if (e.which == 32) {
    if (video.paused) {
      video.play();
    } else {
      video.pause();
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<video controls id="vid" style="width: 400px; display:block;">
  <source src="https://interactive-examples.mdn.mozilla.net/media/cc0-videos/flower.webm" type="video/mp4">
</video>
<input type="text" value="write here!">

  • Related