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.  

Change The Color Of A Movie Clip


setColor(mc, 0xFF0000); //Changes the color of the movieclip to red

function setColor(mc, color):void {
var colorTransform:ColorTransform = mc.transform.colorTransform;
colorTransform.color = color;
mc.transform.colorTransform = colorTransform;
}

Right-Click Context Menu


var menu:ContextMenu = new ContextMenu();
menu.hideBuiltInItems();
var menuItem:ContextMenuItem = new ContextMenuItem("Go to google");
menuItem.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, goToContextMenu);
menu.customItems.push(menuItem);
this.contextMenu = menu;

function goToContextMenu(event:ContextMenuEvent):void {
var link:URLRequest = new URLRequest("http://www.google.com");
navigateToURL(link,"_blank");
}

Center A Display Object


centerObject(obj); //Centers a display object

function centerObject(obj:DisplayObject):void {
obj.x = stage.stageWidth / 2 - obj.width / 2;
obj.y = stage.stageHeight / 2 - obj.height / 2;
}

Draw A Triangle


var triangle:Shape;

drawTriangle(0, 10, 100, 0xFF0000);

function drawTriangle(x:Number, y:Number, height:Number, color:uint){
triangle = new Shape;
triangle.graphics.beginFill(color);
triangle.graphics.moveTo(height/2, y);
triangle.graphics.lineTo(height, height+y);
triangle.graphics.lineTo(x, height+y);
triangle.graphics.lineTo(height/2, y);
addChild(triangle);
}

Draw A Circle


var circle:Shape;

drawCircle(100, 100, 75, 0xFF0000);

function drawCircle(x:Number, y:Number, radius:Number, color:uint){
circle = new Shape;
circle.graphics.beginFill(color);
circle.graphics.drawCircle(x, y, radius);
circle.graphics.endFill();
addChild(circle);
}

Draw A Rectangle


var rectangle:Shape;

drawRectangle(0, 0, 200, 200, 0x0000FF); //Draws a rectangle at the origin

function drawRectangle(x:Number, y:Number, width:Number, height:Number, color:uint){
rectangle = new Shape;
rectangle.graphics.beginFill(color);
rectangle.graphics.drawRect(x, y, width, height);
rectangle.graphics.endFill();
addChild(rectangle);
}

Convert Degrees To Radians And Radians To Degrees


var degrees = 90;

var radians = degreesToRadians(degrees);
degrees = radiansToDegrees(radians);

trace(radians); //Outputs 1.57
trace(degrees); //Outputs 90

function degreesToRadians(degrees:Number):Number {
return degrees * Math.PI / 180;
}

function radiansToDegrees(radians:Number):Number{
return radians * 180 / Math.PI;
}

Determine Whether Number is Even or Odd


function isEvenOdd(num):String {
if ((num % 2) == 0) {
return "even";
} else {
return "odd";
}
}

trace(isEvenOdd(2)); //Outputs even
trace(isEvenOdd(7)); //Outputs odd

Generate Random String


function generateRandomString(strlen:Number):String{
var chars:String = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var num_chars:Number = chars.length - 1;
var randomChar:String = "";

for (var i:Number = 0; i < strlen; i++){
randomChar += chars.charAt(Math.floor(Math.random() * num_chars));
}
return randomChar;
}
trace(generateRandomString(7));

Load And Parse XML File

XML File:



picture1.jpg
picture 1
picture 1 description


picture2.jpg
picture 2
picture 2 description


picture3.jpg
picture 3
picture 3 description




Actionscript:


var xmlLoader:URLLoader = new URLLoader();
var xmlData:XML = new XML();
xmlData.ignoreWhite = true;
xmlLoader.addEventListener(Event.COMPLETE, loadComplete);
xmlLoader.load(new URLRequest("slideshow.xml"));

function loadComplete(e:Event):void {
xmlData = new XML(e.target.data);
for each (var picture:XML in xmlData.picture) {
trace("Url: " + picture.url);
trace("Heading: " + picture.heading);
trace("Description: " + picture.description);
}
}

Determine Whether Number is a Prime Number


function isPrime(num) {
for (var i=(num-1); i > 1; i--) {
if ((num % i) == 0) {
return false;
}
}
return true;
}

trace(isPrime(2)); //Outputs true
trace(isPrime(4)); //Outputs false
trace(isPrime(17)); //Outputs true

AS3 mailto


var email:String = "mailto:youremail@address.com";

button.addEventListener(MouseEvent.MOUSE_DOWN,sendEmail);

function sendEmail(e:Event):void {
navigateToURL(new URLRequest(email), "_self");
}

Create Empty MovieClip

Here is a snippet that creates an empty movieclip. This is useful when you want to load external images or swfs into it.

var emptyMovieClip:MovieClip = new MovieClip();
emptyMovieClip.name = "emptymc";
addChild(emptyMovieClip);

Create Dynamic Textfield


var exampleTextField:TextField = new TextField();
exampleTextField.text = "your text goes here";
exampleTextField.width = 200;
addChild(exampleTextField);
exampleTextField.autoSize = TextFieldAutoSize.LEFT;

var format:TextFormat = new TextFormat();
format.color = 0x990000;
format.size = 20;
exampleTextField.setTextFormat(format);

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