Setting Keyboard Focus to YouTube Embed

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) {

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.

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");
  if(event.keyCode== 32){
    if(player.getPlayerState() == 1){

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
jquery move up/down excluding element

jquery move up/down excluding element

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

Only keep one div expanded

Only keep one div expanded

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

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:

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