views:

4151

answers:

5

I have the following javascript being called to request a focus when page is loaded.

This code works 100% OK with Firefox and IE7, but Chrome and Safari do not seem to move the focus at all. How to make it work with all browsers?

 document.getElementById("MyFlashFile").focus();
A: 

Ensure this code is being called after the entire page has been rendered. It's probably being called above the HTML it refers to, so the element will not exist yet.

Various JavaScript frameworks have utilities to tell you when the DOM is ready.

Diodeus
+3  A: 

Unfortunately there is no way to ensure that you can set focus to a flash file that works in all browsers. IE and Firefox have solved this problem (for the most part), but Chrome and Safari are both based off of Webkit which does not have a solution.

If you ever notice on YouTube or other video / flash site that the first thing you see is something to entice you to click on the player, that is due to this problem.

One developer came up with a clever workaround, but it does involve adding some ActionScript to your flash file, this can be a pain in the ass if you are building a generic player.

Gary Bishop: Fixing Firefox Flash Foolishness

Another sort of solution is to set your wmode to opaque. I've heard this works in some situations, but will screw up cursors in text areas. I haven't had much luck with this either, but you can give it a shot.

You can find more information about the no focus bug on bugzilla.

Adam
Adam, check Cláudio Silva's solution below. It worked for me :).
Anvaka
+1  A: 

It seems that there is a bug in Chrome:

"window.document.getElementById('swfID').focus() not working for flash objects"

http://code.google.com/p/chromium/issues/detail?id=27868

I've tried to find a workaround but I was not able to find one ;(

Regards, Christian

Christian Junk
A: 

Your suggestion to change wmode to 'opaque' worked for me great! Thanks, it really saved lot of time for me.

Syamala
+5  A: 

It took me hours searching the Internet, but finally I found a solution that works on the lastest versions of IE, Firefox, Chrome and Safari. The following code solves the problem for good:

<head>
  <script type="text/javascript" src="swfobject.js"></script>
  <script>
    function setFocusOnFlash() {
      var f=swfobject.getObjectById('myFlashObjectId');
      if (f) { f.tabIndex = 0; f.focus(); }
    }
  </script>
</head>
<body onload="setFocusOnFlash()">

This example assumes the flash is embedded using the SWFObject library. If not, you should set the f variable to the Object or Embed tag which holds the flash movie.

Cláudio Silva