Search code examples
javascriptiframeyoutube

Can't Change Focus from Youtube IFrame


I have a Youtube iFrame and I control playback using keyboard shortcuts. However, when I fast-forward/rewind, the focus changes to the iFrame, which captures subsequent key presses. Thus, I use a simple function to poll when focus changes to the iFrame, and then switch the focus back to the document body. Here is the live code:

CODEPEN

However, it doesn't work! Even though document.body.focus() is being called, the focus never changes from the iFrame. Any idea how to fix this?

Note: The browser I'm using is Chrome 41.0.2272.118 on my Surface Pro 3 (Win 8.1)


Solution

  • Seem's like focus() only works on buttons (tested on document.body and regular <p> elements, both do nothing).

    Fixed CODEPEN (old, see update below!)

    Note that I added document.getElementById("btn").focus() before document.body.focus(), yet the focus switches to btn and not document.body. The browser I'm using is Chrome 41.0.2272.118 on my Surface Pro 3 (Win 8.1)

    UPDATE

    Turns out, if the button is hidden using display:none or visibility:hidden, the focus() method doesn't work anymore! This made me suspect that the issue was actually with whether or not an element is focusable or not. Apparently a tabindex of -1 makes an element focusable, so I tested this by setting document.body.tabIndex = -1; before calling document.body.focus(). and lo and behold, IT WORKS!

    updated CODEPEN