Flash focus woes
januari 7, 2010 at 12:18 in Code,English (archived),Flash,Javascript,xHTML No comments
Sometimes your favourite sofware just lets you down. Firefox did so today, when I found out that using focus() on an object works fine in IE(!!) but not always in Firefox 3.5. What I had on my page was a combination of a flash movie, embedded dynamically using SWFObject 2.2, and my flash movie opened a shadowbox when some objects in it were clicked. Now an swf file doesn’t listen to any commands before it is clicked first, which meant you had to click the SWF every time you opened and closed a lightbox, and on every page reload.
Now as it turned out the mistake I made was using this example using the SWFObject event ‘addDomLoadEvent’. Now the event DID fire, but apparently did so too early. I didn’t get any errors on my javascript (so the page WAS loaded) but apparently the SWF hadn’t been added and thus couldn’t be focussed properly.
We need to use a few ugly old HTML tricks, which I personally dislike but in this case do work the best.
Here’s the javascript function (replace the ID here with whatever ID the element that you add your flash to has). I have not tested whether the order in which the two are defined below (my function first, then embedSWF) makes any difference.
1 2 3 4 5 6 | function setupSWFObjectFocus() { var swf = document.getElementById("flash"); swf.focus(); } swfobject.embedSWF("HvaMuur.swf", "flash", "800", "500", "9.0.0", "expressInstall.swf", false, {wmode:"opaque"}); |
Now we need to call this function. I do this in three seperate occaisons: on the body load, when the shadowbox is closed, and when the mouse is over the flash movie.
1 2 3 4 5 6 7 |
As you may have noticed in the code above the onmouseover event listener is on a “flashcontainer” div, and not the div that I actually load my flash movie into. This is because for some reason javascript didn’t listen to the div that held the flash movie, but did listen to a container div that has the same position, width and height, but is invisible as it is positioned behind the flash div.
If you use shadowbox, like me, the code below might be of use. The onClose function is great, but as you can read in my comments in the script it needs a short delay to work.
1 2 3 4 5 6 7 8 9 | <script type="text/javascript">// <![CDATA[ Shadowbox.init({ players:["img","html","iframe"], viewportPadding: "0", //Adding a short delay here because this function actually triggers when the close button is pushed, which means shadowbox is still open and focus will not work onClose:function(){ setTimeout("setupSWFObjectFocus()", 40); } }); // ]]></script> |
I have tested this code in Firefox 3.5 and IE8, but it should work in most browsers.