Flash and JavaScript cross communication p.3

source: http://www.thegoldenmean.com/

The JavaScript

The code isn’t much more involved than the ActionScript was. As before I will show it in its entirety and then dissect it.

var flash;
window.onload = function() {
  if(navigator.appName.indexOf("Microsoft") != -1) {
    flash = window.playsound;
  }else {
    flash = window.document.playsound;
  }
}

function playTrack(track_url) {
  flash.playerPlay(track_url);
}

function stopTrack() {
  flash.playerStop(); 
}

Where does it go?

While JavaScript code can be placed in the <head> element of an HTML document, it is considered good practice to keep scripts in external documents and link to them in the <head> element instead. (Good information on this practice is available at the quirksmode site linked to on the last page of this tutorial.) Accordingly, I saved the above code in a document I named “player.js”

What does it do?

The JavaScript begins by declaring a variable flash, which will hold as a value the Flash movie we just created. It determines the value by using the DOM (Document Object Model). When we embed the Flash movie on the next page we will assign it an ID of “playsound”. JavaScript uses the DOM to locate an element in the HTML with an ID of “playsound” and assign it to the variable “flash”. JavaScript executes this when the page has completely loaded.

Next, two functions are written that echo their ActionScript counterparts: “playTrack()” and “stopTrack()”

When “playTrack” is invoked by a hyperlink in the HTML document, it in turn invokes the “playerPlay” ActionScript function (via the ExteralInterface callback we wrote on the previous page), passing to it the path to the MP3 asset.

When “stopTrack” is invoked by a hyperlink in the HTML document, it in turn invokes the “playerStop” ActionScript function (again via the ExternalInterface callback).

Sweet and simple. Page four ties it all together.

go to page: 1 | 2 | 3 | 4 | 5
divider ornament

--top--