PCoelho
PCoelho

Reputation: 8010

How to focus on a youtube video player object

I am making (or trying to make) a chrome plugin that when entering a youtube page, focuses on the video object automatically.

The reasoning for this is that I like to use the space bar to pause the video. However when we enter a youtube video page, it focus on the body. If you press space then, it just scrolls down.

Here is my code.

var mp = document.getElementById("movie_player");
setInterval(test,2000);
function test(){
    mp.focus();
    console.log(document.activeElement);
}
onload = mp.focus();

I can't seem to focus on the movie_player object. I tried a timer-loop and using the onload. It keeps focusing on the body element.

I know that jQuery can do this no problem. But because the task is so bluntly simple and just needs to work in chrome, I feel jQ is an overkill.

Upvotes: 4

Views: 2595

Answers (1)

Dave
Dave

Reputation: 46329

I just had to solve the same problem. The solution is to set tabIndex first. By default, plugins have an index of -1;

function focusMyFlash(name){
    var t=document[name]||window[name];
    if(t){
        t.tabIndex=0;
        t.focus();
    }
}

This works in Chrome and FireFox, and I assume it still works in IE (but untested so far).

Upvotes: 1

Related Questions