最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Detect focus on HTML5 video - Stack Overflow

programmeradmin2浏览0评论

As when using youtube, if you click on "play" or "pause" the focus is on the video and using spacebar will pause or play the video.

In the same line, I would like to prevent the spacebar action after playing on a HTML5 video. To do so I was trying to detect the focused element, but it seems the video element doesn't get the focus event in the same way.

I tried using jQuery for it:

$(':focus');

And plain Javascript:

document.activeElement

None with success.

As when using youtube, if you click on "play" or "pause" the focus is on the video and using spacebar will pause or play the video.

In the same line, I would like to prevent the spacebar action after playing on a HTML5 video. To do so I was trying to detect the focused element, but it seems the video element doesn't get the focus event in the same way.

I tried using jQuery for it:

$(':focus');

And plain Javascript:

document.activeElement

None with success.

Share Improve this question asked Jul 8, 2016 at 10:39 AlvaroAlvaro 41.6k31 gold badges172 silver badges348 bronze badges 1
  • What are you actually trying to do? If you are trying to prevent space from interacting with the video, I would suggest adding an event handler on the video that detects if the sapce bar has been pressed, and ignores it. – Ian Devlin Commented Jul 8, 2016 at 10:56
Add a ment  | 

3 Answers 3

Reset to default 3

Add an event listener to your video element and on play event focus some other(focusable) element on the page e.g a dummy button which does nothing

var video=document.getElementById("MyVideo");

video.addEventListener('play', function () { 
  document.getElementById("myDummyButton").focus();
});

this will take away the focus from your video element to the dummy button as soon as the video is played. You can also do the same for pause event.

And carefully place the button close to your video element because focussing it will cause the page to scroll if it is placed somewhere below in the page off the screen. Also keep in mind that all types of elements are not focussable.

Use like this:

document.getElementByID("video").onfocus = function(){}

You can add a key event handler so you can filter out key events on the video element.

video.addEventListener("keydown", function(evt) {
  /* check the key you don't want and if hit call: */
  evt.preventDefault();
}, false);

You can force the element to take focus by specifying a tabindex attribute if it doesn't already

<video tabindex="1" /* etc. */ ></video>
发布评论

评论列表(0)

  1. 暂无评论