Belaviyo
Belaviyo

Reputation: 187

Focus dynamically created embedded YouTube player

So I need to open an embedded YouTube player in a website, and I would like to set the focus to the player so that users can interact with the player like for instance toggle the video using the Space key.

var iframe = Object.assign(document.createElement('iframe'), {
  src: 'https://www.youtube.com/embed/hLQl3WQQoQ0?autoplay=1&enablejsapi=1',
  width: '400',
  height: '200',
  onload: () => {
    console.log('iframe is loaded!');
    iframe.focus();
  }
});

document.body.appendChild(iframe);

This code inserts the player, and onload is called but the player still does not get the focus. Any idea if this is doable or not?

Upvotes: 0

Views: 1551

Answers (1)

Vitor Costa
Vitor Costa

Reputation: 114

You would need to focus on the document inside the iframe to achieve this, which is not possible due to security reasons.

However, you can add a hidden button input, focus on it, and then use keyCode and the player API from youtube to pause and play the video in the case you press the space bar on that focused input of yours.

Have a look on this answer, and on the codepen it links to.

Upvotes: 1

Related Questions