Setting Keyboard Focus to YouTube Embed

381
November 26, 2016, at 9:49 PM

I’m trying to find a way to get the keyboard to focus on the YouTube player in my page. This could, for example, make it easy to use the space bar to play/pause the video.

Here’s an example: Testing Embed Keyboard Focus (CodePen)

As it is, I’m having to click on the player for it to be able to accept keyboard shortcuts. Because this is not ideal, I’m hoping for a workaround using Javascript or jQuery to set the focus on the video.

I’m aware that – as an alternative – I could use the spacebar key to call the player object's playVideo or pauseVideo methods, but that still wouldn’t get me access to the full list of the YouTube player’s keyboard controls.

And if this is simply impossible, I’ll understand. But it will be nice to know. Thanks!

Answer 1

In order to achieve this you would have to focus() document embedded in the Youtube's iframe. This is restricted by Same-origin policy for security reasons.

Here's a piece of code for completeness

function onPlayerReady(event) {
    document.querySelector('#player').contentDocument.body.focus(); 
}

And it would throw

Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement':

Answer 2

You can do something like this to implement whatever hotkeys you want to enable for the player at any rate.

http://codepen.io/anon/pen/jbgeYo

Basically you create an input (can style it so that it blends in, you can't do display:none as that won't let you assign focus), and then attach a keypress event to that input. You then can call functions on the "player" API object which allows you to play/pause etc.

var dummy=document.getElementById("dummyFocus");
dummy.focus();
dummy.addEventListener("keypress",function(event){
  if(event.keyCode== 32){
    if(player.getPlayerState() == 1){
      player.pauseVideo();
    }
    else{
      player.playVideo();
    }
  }
});

Insert that after you create your player object, and add an input (I used type="button") to the page with id="dummyFocus"

Edit as needed, but that's a workaround anyway.

Rent Charter Buses Company
READ ALSO
jquery move up/down excluding element

jquery move up/down excluding element

I am trying to move thedraggable div up and down, bypassing the

391
Only keep one div expanded

Only keep one div expanded

I'm using simple-expand Jquery plugin (http://sylvain-hamelgithub

279
jQuery - Call a function on an element

jQuery - Call a function on an element

I want to call a function to show and modify content like this:

388
Angular - Lazy Load List

Angular - Lazy Load List

One of the select drop downs for my application has a huge number of items,to the point it's causing a slight delay on page load

406