Monday, October 25, 2010

Creating a custom double click function in AS3

Today we will create our own double click function, where we set the interval.

Sometimes, it is needed to have a double-click feature on some buttons, and we can use the DoubleClick event for that. But there's one problem - the interval between two clicks in a doubleclick is set in each user's system options and we aren't able to control it. But what if we need to? We can create our own function then.

I will create a function, that will have 3 parameters - one for the button I want to apply this double click, one for the function to call on double click and one for the delay time.

Here's an example:

And here is the code for my function:

function DoubleClick(button, functionToCall:Function, delayInMS:Number):void
var timer:Timer = new Timer(delayInMS,1);
timer.addEventListener(TimerEvent.TIMER_COMPLETE, timerManager);
function timerManager(TimerEvent):void

button.addEventListener(MouseEvent.CLICK, clickManager);
function clickManager(MouseEvent):void
if (timer.running)
if (! timer.running)

How does it work?

First of all, an instance of Timer class is created. This will manage the time between clicks. The delay is set to the number set in the parameter of our function. When the timer completes a cycle - we reset our timer.

When the button is clicked once - we check whether the timer is running. If it is, then it's a double click (timer is being reset and the action function is called). If it isn't, then it's the first click and the timer starts again, so that we can perform a double click if we click once more.

So, to use the function:

DoubleClick(myButton, actionFunction, 500);

Thanks for reading!


Double clicking in AS3

1 comment:

Alastair Reece said...

This is AWESOME. exactly what I needed and saved me the time of building it/figuring it out myself! Cheeers buddy and well done!

Post a Comment