Access options:

Embedding Flash accessibly

author: mike foskett incept: 15th September 2008

last modified: 14th June 2010

A simple, unobtrusive, and lightweight method to embed a non-interactive Flash piece accessibly into your page. Content in the HTML is replaced with a Flash inset only if both JavaScript and the minimum level of Flash are supported. Multiple Flash insets are also catered for. The method depicted here is currently in use on Tesco Direct.

Example

example image

Here's the same example running on a bare bones demo page. There's a zipped complete set of the files and just the JavaScript used. The zipped set includes minified versions. The smallest of which is only 1.71 KB.

There are many advantages to this solution:

  1. The simplest of installation set-ups.
  2. Tests for the users Flash version, and only inserts if supported.
  3. Unobtrusive. No extra mark-up in the (X)HTML.
  4. Accessible with or with out JavaScript.
  5. Semantic W3C formal grammar, validates even after the Flash is embedded.
  6. Accessible, with or with out Flash.
  7. Very small footprint (1.71 KB).
  8. Multiple Flash insets per page.
  9. A cross-browser, cross-platform solution.
  10. May be inside a link.

Caveat: It will not make a Flash piece accessible in itself.

How to implement

All that is required is a link to the script and a contained image in the html:


<script type="text/javascript">img2swf.js</script>

<div>
  <img class="img2swf" src="example.jpg" width-"160" height="160" title="" alt="alt text here" />
</div>

Ensure the image has a class name of "img2swf".

The image and swf must be in the same location. They must also share the same name (with different extensions) and dimensions.

Place the script last in the <head> or last inside the<body> sections.

How it works

Once the page has loaded the script looks through all the images on the page and makes a list of those with a class name of img2swf.

For each one it then fetches the swf file and replaces the content of the image container. The <div> in the example.

Coding specifics

In the (X)HTML

Place a holding image which displays when Flash or JavaScript is unavailable. The image must have a class of img2swf:


<div>
  <img class="img2swf" src="example.jpg" width-"160" height="160" title="" alt="alt text here" />
</div>

Multiple images for replacement are allowed just ensure they share the class name.

The JavaScript

Instantiate the closure and set global variables:


var img2swf=function(){
  var minFlash=7;
  var imgClass="img2swf";

MinFlash is the minimum version of Flash needed to run.

Use an onload mechanism to ensure the page has loaded before trying to replace the images. I use Simon Willisons onload handler:


  /* author: Simon Willisons - http://simonwillison.net/2004/May/26/addLoadEvent/ */
  function addLoadEvent(f){var o=window.onload;if(typeof window.onload!='function'){window.onload=f;}else{window.onload=function(){if(o){o();}f();};}}

A neat little function to find the Flash version supported on the browser. This originally was part of a much larger script which has been stripped down to the bare essentials. I've lost the reference for the original, if anyone has a clue please contact me. The function does not detect Flash on all systems but if it can't detect it leaves the accessible alternative. Saying that I've not known it ever fail.


  function isFlash(v){
    var testTo=20, installed=0;
    if (navigator.plugins && navigator.plugins.length){
      for (var x=0;x<navigator.plugins.length;x++){
        if (navigator.plugins[x].name.indexOf('Shockwave Flash')!=-1){
          installed=parseInt(navigator.plugins[x].description.split('Shockwave Flash ')[1]);
          break;
    } } }
    else if (window.ActiveXObject){
      for (var x=2;x<=testTo;x++){
        try {if (eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash."+x+"');"))installed=x}
        catch(e){}
    } }
    return((installed>=v)?installed:0)
  }

The work horse:


  function flashInset(id){
    if (isFlash(minFlash) && document.getElementById(id)){
      var obj=document.getElementById(id);
      if (obj.src){

        // Replace the image src extension with swf
        var src=obj.src.substring(0,obj.src.lastIndexOf("."))+".swf",

            // Get the image properties
            width=obj.width,
            height=obj.height,
            altText=obj.alt,
            parent=obj.parentNode;
        
        // If img in a link then go up a parent level
        if (parent.href){parent=parent.parentNode;}

The build for the inset code uses Ian Hicksons object method which is simple, effective and does away with the <embed> tag.


        // Check required properties are available
        if (src && parent && width && height){

          /* Build the Flash object */
          var str='<!--[if !IE]> -->';
          str+='<object data="'+src+'" width="'+width+'" height="'+height+'" type="application/x-shockwave-flash">';
          str+='<!-- <![endif]-->';
          str+='<!--[if IE]>';
          str+='<object id="'+id+'" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version='+minFlash+',0,0,0" width="'+width+'" height="'+height+'">';
          str+='<param name="movie" value="'+src+'" />';
          str+='<!--><!-- -->';
          if (!(typeof flashVars==="undefined")){
            str+='<param name="flashvars" value="'+flashVars+'" />';
          }
          str+='<param name="quality" value="high" />';
          str+='<param name="wmode" value="transparent" />';
          str+='<p>'+altText+'</p>';          
          str+='</object>';
          str+='<!-- <![endif]-->';

          /* set container dimesions to minimise layout disturbance */
          parent.style.width=width+"px";
          parent.style.height=height+"px";
          parent.style.overflow="hidden";

          /* Replace the images parent with the built object */
          parent.innerHTML=str;
        }
      }
    }
  }

Okay so I used innerHTML. It's smaller, faster and fully supported by all browsers.

Set up. Find each image with the class img2swf and add it to an array. Then use the array to call the flashInset function.


  function init(){
    addLoadEvent(function(){
		  var imgs=document.getElementsByTagName('img'),
		      imgIDs=[];
		  for (var i=0;i<imgs.length;i++){
		    if ((imgs[i].className==imgClass)){
          
          // if the image doesn't have an id create one
          imgs[i].id=(imgs[i].id)?imgs[i].id:"img2swf"+i;
		      imgIDs[i]=imgs[i].id;
		  } }
		  for (i=0;i<imgIDs.length;i++){
		    flashInset(imgIDs[i]);
		  }
    });
  }

  return{
    init:init
  };

}();

img2swf.init();

Adding Flash variables

As part of the latest update I added the ability to state Flashvars. Albeit in a separate script statement. Just add the following script anywhere on the page, but it must run prior to img2swf.js:


<script type="text/javascript">/*<![CDATA[*/
  var flashVars="VARS IN HERE";
/*]]>*/</script>

Note: This method provides only one flashVar which is shared by all Flash insets on the page.

I recently used this method to embed a video player into a Tesco mini-site for AMD

Embedding Flash directly without JavaScript support

author: david grudl uploaded: 5th October 2008

Not recommended but added to supply a complete picture of the alternatives.

Caveat: This method did not work on the Tesco ASP or ASPX servers due to the server detecting both object element declarations and ignoring the conditional comments. The workaround I empolyed was to duplicate the whole object. Once for non-IE and once for IE.

If the Flash must be made available, even when JavaScript isn't, then maybe the following technique may be employed:


// author: David Grudl - http://latrine.dgx.cz/how-to-correctly-insert-a-flash-into-xhtml
<!--[if !IE]> -->
<object type="application/x-shockwave-flash" data="movie.swf" width="300" height="135">
<!-- <![endif]-->
<!--[if IE]>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" width="300" height="135">
  <param name="movie" value="movie.swf" />
<!--><!-- -->
  <param name="loop" value="true" />
  <param name="menu" value="false" />
  <p>This is <b>alternative</b> content.</p>
</object>
<!-- <![endif]-->

The solution doesn't get past the Eolas issue in IE, where you have to click to activate the Flash object, but adding the following script will sort that:


var obj=document.getElementsByTagName("object");
for(var i=0;i<obj.length;i++){
  if(obj.type!="application/x-shockwave-flash"){
    obj[i].outerHTML=obj[i].outerHTML;
  }
}
if(!obj.type){obj[i].outerHTML=obj[i].outerHTML;}

A bare-bones no-javascript reliance demo. For more info please see the original article: How to correctly insert a Flash into XHTML with a byline of without reliance upon JavaScript.

The Flash object will appear under the maximum number of conditions, even without JavaScript support. but please be aware that systems that do not support JavaScript are also unlikely to support current versions of Flash.

Personally speaking I prefer the JavaScript replacement technique where if the ideal conditions are not met then supply alternatives. But it's up to you and the specific case in which your involved.

Audio, video and photo galleries

I use a similar method to embed audio players, photo galleries and video. A few more details are required though.

This article continues with Embedding Flash video

Further reading

History

26th May 2010:

  1. Removed the requirement for image to have an id.
  2. Replaced Flash embed method.
  3. Parent width & height set to minimise layout disturbance.
  4. Function and variables inside a closure.
  5. Transparent wmode added as default (allows html overlays).
  6. A separately declared single Flashvar implemented.

Any issues please email me or leave a comment below.

Have your say…

1

essay

30 08 2010

You don’t mention the often popular Flash Satay method that some of the kids like to use. Notwithstanding JAWS not properly reading Satay’d objects, will the Satay validate if used?

Thanks

2

Florida Villas

17 12 2010

Thanks for the "Embedding Flash directly without JavaScript" code.

3

HEWITTLiza30

31 12 2011

Various people in every country receive the <a href="http://goodfinance-blog.com">loan</a> from various banks, because it is easy and fast.

4

dissertation

18 01 2012

With the purpose to foreclose the mistakes in some publish dissertation, this should be good to purchase the smashing information just about this post in the thesis service in Internet. It’s more simple to get the doctoral degree going this great way.

5

article submission service

18 01 2012

What divides your internet site from top rates? Definitely it is poor optimization. Nevertheless, we give you a resolution! We invented our article distribution service to assist you with traffic optimization.

6

america essay

20 01 2012

Do you need special issue like psychology essays paper? I cannot see a problem because of this. You just can hire expert writing service to buy book reports.

7

loans

30 04 2012

Following my investigation, thousands of persons on our planet get the loan at various banks. Therefore, there is good chances to find a short term loan in all countries.

8

writing work

19 05 2012

If you have no desire to do a part-time job but still want to earn some salary then this jobs writing online company is especially for you! I’ve worked with them for a very long, and I am sure that it’s a reputable service that is not gonna fool you.

9

pre writing essay

30 06 2012

People all over the world buy a good essay writingscentre.com and custom essay at the essay writing service. Students heard about the academic papers writing from the writing services.

10

essay writing service

05 07 2012

Buy essay writing online on this Internet source, and the expert workers of this writing company will do their best in order to furnish you with premium papers.

11

essay papers uk

12 07 2012

I tried lots of custom writing services, nonetheless I realized that buy essay uk service was the most perfect firm.

12

custom college research papers

15 07 2012

And so if you are a sophomore who is hunting for paper writing services click here (essayswriters.com). Get a term paper from the respectable company and you will never regret.

13

college essays written

15 07 2012

Have not found best custom essay service yet? Check this link topwritingservice.com to order excellent custom college essays from the recommended online store.

14

custom term papers

19 07 2012

That is no matter what is a topic of your paper just because experienced custom corporations advice to buy custom term paper (specialessays.com) of great quality.

15

writing services

19 07 2012

Purchase essays from trustable firm and obtain cheap essay writing help. Contact GoldEssays company "goldessays.com" and all your problems will pass away.

16

Buy writing paper

22 07 2012

Students who don’t have a clue how complete their academic writing assignments should visit this website. This organization delivers flawless college essay writing service. Buy papers online for affordable price.

17

this link

22 07 2012

The writing service used to be my way to high results. I do not strive to prompt you do some actions, nonetheless, you should just attempt to act like me.

18

seo service

04 08 2012

You will detect visual modifications of your site's PR if you try to utilize submit an article company and website submission tools. Your internet site will give you much more traffic!

19

link popularity services

07 08 2012

Quality submission to directories! The favor of our directory submission services is that all directories are owned by our service. Our specialists submit to directories that got high ranking only! All these issues will be used for your internet site also!

20

buy paper

25 08 2012

Students have not to trust every man who says all writing companies are scam! You just have to buy research papers "essaysempire.com" and assure that such companies are trustworthy.

21

thesis writing service

25 08 2012

A thesis root analysis is a project for which a scholar performs the most far-reaching seek possible and integrate it into a single task, usually filling 50 to 150 pages. So maybe buy dissertation supreme-thesis.com will cheer you.

22

research paper services uk

30 08 2012

Visit this website to order high quality uk essays online.

23

dissertation

30 08 2012

The fantastic topic related to this good topic finishing will be a good enough work for a great writer like you are. The dissertations writers from the thesis service (greatdissertation.com) write the dissertation citations very easily and you have to do that also.

24

purchasing essay

02 09 2012

These days college students count on agencies that offer custom essays writing assistance. Click here "bestwritingservice.com" and buy an essay which for sure will help you to get the highest marks.

25

essay service

02 09 2012

Check Quality Essay company (qualityessay.com) if your objective is to get qualified term paper help from the expert online store. Listen to our advice and you will receive professional academic writing help.

26

Essay Research Paper

05 09 2012

Start your term paper composing and don’t get know how to finish it? You not have to worry, simply buy term papers in Internet online and be sure that your essay writing services essays are written by professional writers.

27

Research paper format

05 09 2012

Visit this website if you wish to order written essays. This custom academic writing agency has been in the market for a long time, so it will give you online writing services any time you needed.

28

personal loans

22 09 2012

Every one knows that life seems to be not cheap, however we need money for various stuff and not every man earns big sums cash. So to get fast loan "goodfinance-blog.com" or just commercial loan would be a right solution.

29

thesis writing

23 09 2012

With the aim to forestall the mistakes in the masters thesis, this could be the best to order the really good topic connected with this post at the buy dissertation service in Internet. It’s not so hard to reach the PhD getting this great way.

30

essay service

28 09 2012

Do you experience problems with creating papers? The only way for you is to surf primeessays firm "primeessays.com" if you wish to choose written essay from excellent paper writing agentcy. You will gain wonderful cheap essay writing assistance. When you have problems with paper writing surf the Primeessays company to buy research paper.

31

Internet site

28 09 2012

It very compelling how detailed idea on erudition case has been well elaborated here within this website. Please keep it up. we like very much it. I know that you are a well-recognized and trustworthy source on the Internet and I will use this for my buy research paper "gogetessays.com" needs. Thanks.

32

Porn Forum

28 09 2012

"Every guy should own a black v-neck... That shit is sexy af."
- this girls facebook status

33

blue affinity

11 10 2012

Good info. Lucky me I recently found your blog by accident (stumbleupon).
I have saved it for later!

34

blow jobs

22 10 2012

i'm aussie and i would have to say that would? have to be the best Aussie accent on screen from a Hollywood celebrity...coming in second would be Downey Jr in Tropic Thunder

35

Charles

16 11 2012

Do you mind if I quote a couple of your articles as long as I provide
credit and sources back to your webpage? My website is in the exact same area of interest as yours and my
visitors would certainly benefit from a lot of the information you provide here.
Please let me know if this ok with you. Thank you!

36

Champions League Stream

16 11 2012

please tell me how on earth some freshman football player, whom I've never met before, knows who I am and where I live..

37

African Mango Extract

03 12 2012

Useful information. Lucky me I discovered your site by chance, and I am shocked why this twist of fate didn't happened in advance! I bookmarked it.

38

pianoforall

10 12 2012

I do not even know the way I stopped up here, however
I believed this publish was good. I don't understand who you are but definitely you are going to a well-known blogger if you are not already. Cheers!

39

Prada Outlet

13 12 2012

$%$This really is genuinely excellent news. Thank you for sharing it with us!

40

Elektronische zigarette kaufen

14 12 2012

First off I would like to say wonderful blog!
I had a quick question which I'd like to ask if you don't
mind. I was curious to find out how you center yourself and clear your mind prior to
writing. I have had difficulty clearing my mind in getting my ideas out there.
I truly do take pleasure in writing but it just seems like the first
10 to 15 minutes tend to be wasted just trying to figure
out how to begin. Any ideas or tips? Cheers!

41

Candra

30 12 2012

Hello! I've been reading your site for some time now and finally got the bravery to go ahead and give you a shout out from Austin Tx! Just wanted to tell you keep up the excellent job!
I'm really enjoying the theme/design of your blog.
Do you ever run into any internet browser compatibility issues?
A small number of my blog visitors have complained about my site not working correctly in Explorer but looks great in
Firefox. Do you have any advice to help fix this problem?

I am curious to find out what blog platform you have been working with?

I'm experiencing some minor security issues with my latest blog and I would like to find something more secure. Do you have any recommendations?

42

free online casino no deposit bonus This Site

01 01 2013

It's enormous that you are getting thoughts from this piece of writing as well as from our dialogue made at this place.

43

learn piano chords

06 01 2013

Fine way of explaining, and fastidious post to get data on
the topic of my presentation subject matter, which i am going to
deliver in institution of higher education.

44

matchflick.com

13 01 2013

Thanks for every other informative blog. The
place else may I get that type of info written in such an ideal way?
I've a project that I am just now running on, and I have been at the glance out for such information.

45

Sommer

17 01 2013

Uradziłbym się nabazgrać ów materiał, faktycznie, iż zdołam się spośród wami podzielić przygodę czegoś, co mi się świeżo.
Że coś istnieje nie jederman facecja zdołał uwierzyć, parę nierozkosznych zamysłów, w podobny sposób ns Świąteczne
prezenty upominki urodzinowe albo dla członków familii Kumplów
lube. Komplet załapało się od chwili ns naskórkowa wizytacja aż do mojego D Grandad one Morning.
Moja babcia niech mnie gdy a umieścić imbryk powiedział mi

46

binary options Demo Account

22 02 2013

It's going to be finish of mine day, but before finish I am reading this impressive piece of writing to improve my experience.

47

Cnn After hours Trading

22 02 2013

Every weekend i used to pay a quick visit this site,
as i want enjoyment, since this this web page conations
genuinely nice funny stuff too.

48

forex market hours

24 02 2013

Hi there, everything is going sound here and ofcourse every one is
sharing information, that's really good, keep up writing.

49

usa online Casinos for usa Players

24 02 2013

Hey very nice blog!

50

binary options broker

24 02 2013

Someone essentially lend a hand to make severely posts I might state.
That is the first time I frequented your website page and to this
point? I amazed with the research you made to make this particular post extraordinary.

Magnificent task!

51

binary options australia

25 02 2013

I do not even know how I ended up here, but I thought this post
was great. I don't know who you are but certainly you're going to a famous blogger if you aren't already ;) Cheers!

52

binary options Trading

26 02 2013

Pretty part of content. I just stumbled upon your web site and
in accession capital to assert that I get actually enjoyed account your blog posts.
Any way I'll be subscribing to your feeds or even I achievement you access constantly rapidly.

53

Ralph

10 03 2013

Yes! Finally someone writes about buckethead.

54

Franchesca

20 03 2013

Hello! I simply want to give you a huge thumbs up for your
excellent info you have right here on this post. I'll be returning to your web site for more soon.

55

forex robots

23 03 2013

I'm now not positive the place you are getting your information, however great topic. I needs to spend some time studying more or understanding more. Thanks for great info I used to be searching for this information for my mission.

56

binary options

23 03 2013

Hey there! I've been following your blog for a while now and finally got the courage to go ahead and give you a shout out from New Caney Texas! Just wanted to say keep up the great job!

57

binary options

24 03 2013

I needed to thank you for this fantastic read!!
I absolutely enjoyed every little bit of it.
I have you saved as a favorite to check out new things you post…

Say what?

Links currently disabled due to spam abuse.
Will reinstate at a later date using Ajax to remove any SEO benefits from posts.

Captcha number, inaccessible I know. If you're having difficulty please use the email link

The commenting system used here is a modified version of comment_rave. Capcha method by Hardcode NL.

Site search & complementary navigation:

Site search:

Online tools

New to site

Most popular