Welcome to my actionscript snippet library!

Actionscript Snips is a small repository of actionscript code that aims to save developers and designers time when developing a website.  

Load Sound


import flash.events.Event;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.net.URLRequest;

var urlRequest:URLRequest;
var sound:Sound;

function loadSound(url:String):void {
urlRequest = new URLRequest(url);
sound = new Sound();
sound.addEventListener(Event.COMPLETE, loadSoundComplete);
sound.load(urlRequest);
}

function loadSoundComplete(e:Event):void {
sound.play();
}

loadSound("sound.mp3");

Convert String To Number


var str:String = "10";
var num:Number = Number(str);

Get Current Date


var currentDate=new Date();
var month=currentDate.getMonth();
var day=currentDate.getDate();
var year=currentDate.getFullYear();

trace(month+"-"+ day + "-" + year);

setInterval

Code snippet that calls a function after one second intervals and stops when the counter limit is reached.

import flash.display.Sprite;
import flash.utils.*;

var duration:Number = 1000;
var intervalId:uint;
var counter:uint = 0;
var endCount:uint = 10;

intervalId = setInterval(myFunction, duration, "start");

function myFunction():void {
trace(arguments[0]);

counter++;
if(counter == endCount) {
trace("end");
clearInterval(intervalId);
}
}

Removes Whitespace From String


var str:String = "action script";

function removeWhiteSpace(str:String):String {
var newstring = str.split(" ").join("");
return newstring;
}

trace(removeWhiteSpace(str)); //Outputs actionscript

Factorial


function factorial(n):Number {
if (n < 2) {
return 1;
}
return n*factorial(n-1);
}

trace(factorial(3)); //Outputs 6

AS3 getURL


var url:String = "http://actionscriptsnips.blogspot.com";
var target:String = "_blank";
navigateToURL(new URLRequest(url), target);

Traversing Array Using For Each Loop


var fruits:Array = new Array("apples", "oranges", "grapes", "pears");

for each (var fruit:String in fruits ) {
trace(fruit); //Outputs apples, oranges, grapes, pears
}

Populate ComboBox

Drag an instance of a combo box onto the stage and give it an instance name.

import flash.events.Event;
import fl.data.DataProvider;

var colors:Array = new Array();
colors[0] = "red";
colors[1] = "blue";
colors[2] = "green";
colors[3] = "yellow";
colors[4] = "purple";

comboBox.dataProvider = new DataProvider(colors);
comboBox.addEventListener(Event.CHANGE, onChange);

function onChange(e:Event):void {
trace(e.target.value);
}

Loading An External Swf

This code can be used to load an external image or swf.

import flash.net.URLRequest;
import flash.display.Loader;
import flash.events.Event;

function loadSwf(swf:String){
var loader:Loader = new Loader();
var request:URLRequest = new URLRequest(swf);
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loadComplete);
loader.load(request);
}

function loadComplete(e:Event) {
addChild(e.currentTarget.content);
}

loadSwf("yourswf.swf");

Count All Occurrences of a Character In a String


var str:String = "programmer";
var char:String = "m";

function countOccurences(str:String, char:String):Number {
var count:Number = 0;

for(var i=0; i < str.length; i++) {
if (str.charAt(i) == char) {
count++;
}
}
return count;
}

trace(countOccurences(str, char)); //Outputs 2

Capitalize First Letter In String


var str = "actionscript";

function upperCase(str:String) : String {
var firstChar:String = str.substr(0, 1);
var restOfString:String = str.substr(1, str.length);

return firstChar.toUpperCase()+restOfString.toLowerCase();
}

trace(upperCase(str)); //Outputs Actionscript

Find Min/Max Of Array Of Integers


var min:Number;
var max:Number;

var numbers:Array = new Array(3, 5, 2, 1, 4);

function findMin(array:Array):Number {
min = array[0];
for (var i = 0; i < array.length; i++) {
if (array[i] < min) {
min = array[i];
}
}
return min;
}


function findMax(array:Array):Number {
max = array[0];
for (var i = 0; i < array.length; i++) {
if (array[i] > max) {
max = array[i];
}
}
return max;
}


trace(findMin(numbers)); //Outputs 1
trace(findMax(numbers)); //Outputs 5


Search And Replace Characters In String

Simple solution for replacing characters in a string

var str:String = "AS3 rocks!";
var search:String = "AS3";
var replace:String = "Actionscript 3";

function strReplace(str:String, search:String, replace:String):String {
return str.split(search).join(replace);
}

trace(strReplace(str, search, replace)); //Outputs Actionscript 3 rocks!

Generate Random Number


function randomRange(max:Number, min:Number = 0):Number
{
return Math.round(Math.random() * (max - min)) + min;
}

trace(randomRange(5)); //Outputs number between 0 and 5
trace(randomRange(10,1)); //Outputs number between 1 and 10

Reverse A String


var myString:String = "reverse";

trace(myString.split("").reverse().join("")); //Output - esrever

Email Validation

Function that validates email.


function isValidEmail(email:String):Boolean {
var emailExp:RegExp = /^[a-z][\w.-]+@\w[\w.-]+\.[\w.-]*[a-z][a-z]$/i;
return emailExp.test(email);
}

trace(isValidEmail("admin@domain.com")); //Outputs true
trace(isValidEmail("admin.@.com")); //Outputs false