Thursday, 16 January 2014

Playing an SWF On Click

When you include an SWF file within a Web page, in most cases it will automatically play when the Flash movie loads. You can prevent embedded SWF files from loading using HTML and JavaScript code in the Web page, but this is not always reliable. If you need an SWF movie not to play straight away but to play when the user clicks it, the most reliable method is to implement this using the ActionScript code within the Flash file itself.

Open the source FLA file for your SWF in Adobe Flash Professional. If the file already has a layer for ActionScript code, select it and open the Actions panel. If it doesn't have an code layer, add a new layer, select it and open the Actions panel. To stop your home timeline from playing when the Flash movie is loaded, add a stop function:
If you have code on different keyframes in the home timeline, add the stop function on the first frame. If your SWF includes Movie Clips which play in the first frame of the home timeline, you will need to add a stop function to them as well. You can stop Movie Clips using their instance names as follows:
Alternatively you can add the stop function to the first frame inside a Movie Clip.

Detect clicks on the SWF. After stopping the movie from playing automatically, you need to prepare your Flash file to detect clicks, so that you can start playback when such clicks occur. Add the following ActionScript code:
stage.addEventListener(MouseEvent.CLICK, startPlayback);
This code instructs the SWF to detect mouse clicks on the stage area, which is the area of the file users can see. When a click on the stage occurs, the function listed as second parameter to the "addEventListener" function, "startPlayback" in this case, will execute.

Play the movie when clicks occur. After adding the mouse event listener to the SWF stage, add the specified function to execute when the user clicks the movie:
function startPlayback(event:MouseEvent):void {
This will cause the SWF's main timeline to begin playback. You can remove the mouse event listener inside this function if you do not want to continue detecting clicks after playback begins:
event.currentTarget.removeEventListener(MouseEvent.CLICK, startPlayback);
If your SWF file has Movie Clips you want to start playing when user clicks occur, list them inside the function and call the play method on them:;
  • You can detect other various user events on the stage, including moving the mouse over and off it.
  • If you have interactive elements within your Flash file, adding a click mouse event listener to the entire stage may interfere with them, especially if you are using other click listeners.

No comments:

Post a Comment