Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

182
Views
How to implement "press space to pause html5 video" except when input is focused? (Jquery)

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.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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!">

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!