snippets

#quick snippet: Count the days between two dates

0

For a project at work I had to display how many days the visitor of the app had left to still join in on the fun. We had a fixed date (the launch of the project) and a variable date (the date of the day that the project visitor actually visited/used the app). So I was in the need of a script that counts the days between two dates. I know, not that hard, but good to have around nonetheless. Quick snippets for the win!

Anyway, the snippet is pretty clear:

- one variable that represents a day (milliseconds times seconds times minutes times hours)
- two dates turned to milliseconds by “getTime()”
- the difference between those milliseconds

The result of that gets divided by the day in milliseconds and voila: a between days counter!

private function getDaysBetweenDates(date1:Date,date2:Date):int {
	var durationDay:Number = 1000 * 60 * 60 * 24
	var date1InMilli:Number = date1.getTime();
	var date2InMilli:Number = date2.getTime();		    
	var differenceInMilli:Number = Math.abs(date1InMilli - date2InMilli)		    
	return Math.round(differenceInMilli_ms/durationDay);
}

Facebook fangate: a how-to with PHP

1

The problem:
You have some awesome content on your facebook page, but you want visitors to like your page before they can read it, aka installing a fangate! No worries, PHP is our friend and this example can be set-up in under five minutes! You can do this with javascript too, but we over at Murten Saerbi choose the PHP way.


Woah… wait! What’s a fangate?
A fangate is actually just a page that checks whether a certain visitor is a fan of your page or not. Therefore this script will only work when you load it in a page. You can do this by creating a new app over on developers.facebook.com and adding the app to your page. The custom pages on Facebook are actually *just* HTML/PHP/… pages that Facebook loads into an iframe.

Like that it looks the content of your website is actually on Facebook inside a custom page tab.


The solution:
First you will need to download the php sdk file, you can do this over at GitHub. Next step is to actually create a php file that you can use as the fangate page. Open up the php tags and start with the base: requiring the file we just downloaded (don’t forget to upload!) and filling in the app id and the app secret. You can find these variables on your application setting screen on developers.facebook.com. Your file should look a bit like this:

<?php
 
require 'facebook.php';
 
$app_id = "your_app_id_here"; 
$app_secret = "your_app_secret_here";
$facebook = new Facebook(array(
        'appId' => $app_id,
        'secret' => $app_secret,
        'cookie' => true
));

After this all we really need is a parameter that tells us if a visitor likes the page he’s viewing or not. You can find this in the signed_request object, a Facebook object that holds various information about the page and the user. Get that object and read out the page_liked parameter:

<?php
$signed_request = $facebook->getSignedRequest();
 
$like_status = $signed_request["page"]["liked"];

When we have the like status inside a variable the rest is easy, a simple if statement will give us the ability to feed the visitor two content pages: one if the user doesn’t like our page yet and one if the user does like our page. That’s about it: easy peasy lemon squeezy! Just don’t forget to close the php code after the if and you’re all set:

if ($like_status) {
echo "<div style='margin-top:0px; position: absolute; top:0px;left:0px; width:520px; height:750px;'>
    <iframe src='HTTP://_THE_PAGE_THAT_NEEDS_TO_BE_SHOWN_WHEN_PEOPLE_LIKE' width='520' height='751' frameborder='0' scrolling='no'></iframe>
</div>";
} else {
echo "<div style='margin-top:0px; position: absolute; top:0px;left:0px; width:520px; height:750px;'>
  <iframe src='HTTP://_THE_PAGE_THAT_NEEDS_TO_BE_SHOWN_WHEN_PEOPLE_DONT_LIKE' width='520' height='751' frameborder='0' scrolling='no'></iframe>
</div>";
}
 
?>

Online you should now have atleast four files:

- the facebook.php file
- the fangate php file (index.php for instance)
- the file that people see when they’re not a fan yet
- the file that people see when they’re a fan

It’s that easy, really: so open up your favourite texteditor and start fan-gating away!

#quick snippet: UNIX Timestamp to as3 Date

0

The problem:
Our flashmovie fetches a Timestamp (UNIX) from some kind of backend code and you need to change this to a workable Date format. It’s actually pretty easy and almost totally standard in flash!


Note:
Flash handles time in milliseconds (think about the timerclass that expects 3000 if you want to time 3 seconds) and the UNIX timestamp is a format based on seconds from the “first day” computers started to use the Gregorian Calendar. In short: the timestamp is defined as the number of seconds elapsed since midnight Universal Time (UTC) of January 1, 1970. Your computer keeps track of how many seconds have elapsed since then and the flash Date class expects this in milliseconds. Simply multiply your seconds with 1000 and you’re done. Easy peasy!


The solution:
A quick code snippet that’s even easy to read for – let’s say – mobile developers!

// replace the capitalized variable with your unix timestamp
// multiply it with 1000 (remember my note above!)
var currDate:Date = new Date(Number(YOUR_TIMESTAMP_HERE)*1000); 
 
// trace out the humanly readable values			
trace(currDate.getDate());
trace(currDate.getMonth());
trace(currDate.getFullYear());



Done!


A real life flash example (DateDisplayer):

Download this wonderful widget here!

Go now, my young actionscript children! Feed on my example and make me proud! Soon the world will be filled with actionscript 3.0 vampires!

basic image gallery #1: circle showcase

0

The intro:
A while ago I made a post about loading images in a grid and an example of how to use the document class. Basic stuff, I know, but it’s a good base to learn/start from.

What I am planning on doing now – I actually already started – is creating a couple of cool ways to display images: basic image galleries. I’m planning on doing a couple so if you have ways that you want me to try out shout them out in the comments.

All galleries will load images out of an xml, so my source files include a custom xml loader. First one up is a circle gallery. All my examples use Tweener for the code animations, so I suggest you download it.

My first example is a circle image gallery by using sine & cosine – that’s Math – which you can see in the preview. The flash file contains alot of comments to explain my actions but it’s really pretty simple once you get the hang of it.


The quick tips:
Flash does not use degrees, but radians. Luckily there’s a simple formula for this:

radian = angle * Math.PI / 180;



The cosine of an angle will give us an x coordinate and the sine of that same angle will give us the y coordinate:

pic.x = Math.cos(radian);
pic.y = Math.sin(radian);



The example:
[kml_flashembed publishmethod="static" fversion="9.0.0" useexpressinstall="true" movie="/blogFiles/gallery_circle.swf" width="530" height="400" targetclass="flashmovie"]

Get Adobe Flash player




The settings:
Inside the xml you can add pictures and choose the radius of the circle.


The aftermath:
You can download the source here. This example is intentionally kept basic but is very versatile and easy to expand. With a little bit of code you can add multiple-page functionality, more animation, maybe even load your flickr account pictures in it with a link to the high-res version! Anyway, the possibilities are endless. Go ahead and try some stuff out! Fly my pretties, fly!

#quick snippet: redirecting to html site when flash is not available

0

The intro:
Say you have people that can’t – or don’t want to – download flashplayer. Then you could use a check with a property of swfobject (the way to go on embedding flash elements). As you may have understood out of the previous sentence: in order for this to work you need to use swfobject. Anyway, on to the code!


The code (this is javascript, not actionscript):

Just add this whole if statement inside a javascript tag, for example the one holding the “swfobject.embedSWF(…” part:

if (swfobject.hasFlashPlayerVersion("9.0.18")) {</code>
// your user has flash and will view your site in flash
} else {
// your user does not have a flash version high enough to view your site and will be directed to google.
window.location="http://www.google.com/";
}



The way this works is: the if statement will be true once the user has flashplayer 9.0.18 or higher. If not they will end up in the “else” and there we redirect the user to google or whatever page you want. I find it works best if you direct them to the html version of your site though.


That’s it! It’s easy peasy! There is also another check that you can add to your swfobject parentheses but this solution is faster and you can specify which flashplayer they need to have (higher versions of flash player work aswell, ofcourse) which is much more powerful in my eyes. The other solution is called a callback (yes, like in flash) of the swfobject method. Just look for “callbackFn” in the api of swfobject if you want to check it out but in my opinion – which should be enough for you – this solution is better.

deeplinking with swfadress part II

5

The intro:
Last year I posted some quick codehints for swfadress and I recently noticed they have released a new version. That’s why I, Murten Saerbi, decided to build a small example for all you freeloaders to use and abuse!

This – atleast I think so – is a seriously useful example. I based all my recent websites on this structure and it can pretty much be used as a base for any flash website that utilizes deeplinking. The keys are the “pageHandler” and the “pageClickHandler” functions in the “Main.as” file. I do not consider this as the only way to implement swfAddress but I find it to be a very easy and versatile technique. I would also really like to thank the man with the golden smile Jannes for his tips on this matter of implementing.

Even if you fully master actionscript 3 and the syntax of swfAddress you can seriously benefit from this example as it contains a way to load your main flash with a separate loader and various other interesting techniques.

note: you will need to get acknowledged with Tweener. It’s not obligatory but I use it in the example so it’s best you know what it does. Get it here. I have included it in the project .zip too.


The example:
The example is a .zip file and can be downloaded here. Or wait no, it’s here. Check an online example of it over here.


The aftermath:
As you can see installing swfadress in a website is no hard work. Having it in a website is even really helpful for your visitors (SEO, direct-page-link, …)!

I can’t really think of a reason that makes you NOT want to include it in your website UNLESS you like dialogs like these:

T. Anthoni Luvs his BabYSt4hr * ElVeS 4-EVAH!:
OMG MURTEN!!!111 LOL!
Murten Saerbi:
What?
T. Anthoni Luvs his BabYSt4hr * ElVeS 4-EVAH!:
Go to www.somepagehere.com then click “about” then “link” then “Tom”
T. Anthoni Luvs his BabYSt4hr * ElVeS 4-EVAH!:
Then click “about Tom” then “personal” then “info” then “contact”
T. Anthoni Luvs his BabYSt4hr * ElVeS 4-EVAH!:
Then click “contact Tom” and you can contact me!

Then you should totally don’t do it. Elves 4-evah!

#quick snippet: using the textformat to style textfields

1

The intro:
Text that has been sent to a database by using “htmlText” instead of plain “text” has certain properties given with it such as ‘color’, ‘font’, etc… . Let’s say you push htmlText into a database and want to read it out in the frontend but you don’t want it to have that saved style. That’s where the textFormat class comes in.


The code:
It’s actually pretty simple once you get the hang of it. First of all you need to add your font to the library. You can do this by clicking on the small arrow with the three lines on the top right of the library panel:

fontscreen screenshot


In the menu that pops up you need to select the option “new Font…”. A box appears where you can set your font, fontname, style and size. By clicking “ok” you can see the font getting added to the library. Right-click it and give it a linkage name you can remember. I will use “Futura”.

From now on it’s just a few lines of code. Import the TextFormat class and if “automatically declare stage instances” is unchecked the font at the top of your class:

import flash.text.TextFormat;
import Futura;


Make an instance of your fontclass and an instance of the TextFormatClass and fill in the properties you want:

var fontFutura:Futura = new Futura();
 
var titleformat = new TextFormat();
titleformat.color = "0x000000";
titleformat.size = 12;
titleformat.font = fontFutura.fontName;


Finally set the textFormat of your textField to the newly created one:

textfield_txt.setTextFormat(titleformat);


Boom. Done.

#quick snippet: right-click menu in as3

0

The intro:
I noticed a friend of mine always builds in a custom right-click menu in his flash websites and decided that this is an excellent code snippet to share with you boys and girls.


The code:
It’s actually pretty simple so here’s the full block. Additional tips are given in actionscript comment style.

// create a new instance of the ContextMenu class
var my_instance:ContextMenu = new ContextMenu();
 
// hide the standard items
my_instance.hideBuiltInItems();
 
// create a new ContextMenuItem by feeding the constructor a piece of text
var menuItem_instance:ContextMenuItem = new ContextMenuItem("made by crazy beaver");
 
// maybe you even want one that has a link behind it
var menuItem2_instance:ContextMenuItem = new ContextMenuItem("crazy beaver");
// add a listener to this item
menuItem2_instance.addEventListener(ContextMenuEvent.MENU_ITEM_SELECT, clickHandler);
 
// push all your menuItems in the ContextMenu instance
my_instance.customItems.push(menuItem_instance, menuItem2_instance);
 
// set the default ContextMenu for your movie to your own contextMenu
this.contextMenu = my_instance;

Don’t forget to create a handler for the items that have listeners to it (in this case “menuItem2_instance”) like so:

private function clickHandler(e:Event):void {
trace("you clicked on the crazy beaver link!");
}

It’s a small snippet, but it’s a nice feature to have and definately worth to implement in your future projects!

#quick snippet: prefilled textfield clearer.

0

The intro:
Every once in awhile you visit a website that has input fields with text in them. No biggie, you say, but when you click on them they don’t get cleared!

That madness should be stopped and here is how!


The code:
Let’s say our textfields are named “name_txt” and “comment_txt”. All you have to do is set a default value. I also added tabIndex, that way users can use the tab button to switch between the two inputfields.

	nameEntry = "your name";
	messageEntry = "your message"
 
	name_txt.tabIndex = 0;
	comment_txt.tabIndex = 1;



And then ofcourse a function to add listeners to “focus in” and “focus out” events and the handlers that go with them.

private function addTheListeners():void {	
	name_txt.addEventListener(FocusEvent.FOCUS_IN, focusInHandler);
	name_txt.addEventListener(FocusEvent.FOCUS_OUT, focusOutHandler);
 
	comment_txt.addEventListener(FocusEvent.FOCUS_IN, focusInHandler);
	comment_txt.addEventListener(FocusEvent.FOCUS_OUT, focusOutHandler);
}
 
private function focusInHandler(e:FocusEvent):void {
	if(e.currentTarget.name == "name_txt") { 
		if(e.currentTarget.text == nameEntry) {
			e.currentTarget.text = "";
		}
	} else {
		if(e.currentTarget.text == messageEntry) {
			e.currentTarget.text = "";
		}
	}
}
 
private function focusOutHandler(e:FocusEvent):void {
	if(e.currentTarget.name == "name_txt") { 
		if(e.currentTarget.text == "") {
			e.currentTarget.text = nameEntry;
		}
	} else {
		if(e.currentTarget.text == "") {
			e.currentTarget.text = messageEntry;
		}
	}
}



Improvements:
You could check on the amount of characters instead of checking on empty strings like I do in the code above. For instance: if there are more than 3 characters in the textfield it is considered “filled in”, otherwise it isn’t. I’m sure you guys can think of some extra requirements to reset a field but like I already said in the title: it’s a quick snippet, there is always room for improvement.

NERDS UNITE!

Basic document class and image grid system.

3

The intro:
I sometimes help out future flash talents with basic examples/code snippets and recently had alot of feedback about one topic in particular.

I can already hear you guys and girls shout: “No time to loose, show me the example!” And right you people are…


The file:
Get it here! (click it, click it!)


What the heck does it do?
Well, it is a flash file with a document class that builds a grid with a for loop. Every grid item loads an image with a custom imageLoading class that is included in the .zip. It is a file to learn from, not to steal from… blah blah, yeah yeah, you can steal it.

Go now, my children! Feed on my example and make me proud! Soon the world will be filled with actionscript 3.0 vampires! Or euhm… *ahum* … humans.

Go to Top