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.  

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);