Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

173
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda