AS3 Buttons and Drag & Drop
In ActionScript 3.0, buttons and interactive movieclip stuff is scripted differently. To understand in depth about how ActionScript 3.0 works for interactivity see the diagram beside.
Diagram besides show, a pin with a tag attached to it. In Action Script 3.0, all events such as mouse clicks, mouse move, mouse over, keyboard inputs, even movieclip’s frame movement is controlled using event listeners. You can attached this event listeners to any movieClip, components, stage or sprites to add interactivity features to it.
Just like how the pin works…just attach the pin to the object.
Each event listeners has a trigger function. Trigger function is a script which triggers because of the specific event for example, a mouse click. This means if you attached an event listener for mouse click on a button, the trigger function itself will be the script for the button. This is how you make button scripts in Action Script 3.0. Similar to our old on(Press) function.
If you have a button with the instance name of Button1, try attaching an event listener for mouse click, to it like example below.
Button1.addEventListener(MouseEvent.CLICK,ButtonClick); function ButtonClick(event:Event){ trace("This button is Clicked!"); }
For drag and drop of a MovieClip, we use two event Listeners. The Mouse_Down and Mouse_Up. For script below you can use MovieClipName.startDrag as trigger function to have a more precise control over it. Sometimes if there’s more than one movieclip inside event.target will specifically target the one the user is clicking – making tat movieclip to be dragged instead of the whole thing
See Example of Flash Below
MovieClipName.addEventListener(MouseEvent.MOUSE_DOWN,DragStart); MovieClipName.addEventListener(MouseEvent.MOUSE_UP,DragStop); function DragStart(event:Event){ trace("Drag Started!"); event.target.startDrag(false); } function DragStop(event:Event){ trace("Drag Stoped!"); event.target.stopDrag(); }
Scripts are available for download here.





Thank you for the tutorial, but I still have a question.
When I click on the pin at the top of the tutorial, the image of the pin is moved to the center of the page, How do you do that? I am creating my first flash site and I want that effect for the contact page but I no idea what it is called or how to make it.
Thanks again.
Bob if u click any of my picture it’s called a javascript lightbox it’s not an actionscript but a javascript. You might wanna do a research on actionscript 3.0 lightbox version.
Lightbox is the effect of dimming the surround,centerizes the focus picture.
If you wanna centerize somthing in flash. Try creating a movieclip containing the form of contact page…when u convert into movie clip make sure the whitespot is centerize. Then exporting into actionscript via linkage. Then in actionscript call out a library movieclip, addChild(movieClipname) make sure u this script like this …movieClipname.x = stage.width/2; movieClipname.x = stage.height/2; that way ur movieclip is always centerize.
Great site. Is there any way to make buttons that can be dragged and dropped?
Basically I want button effects and scripting occuring when I drag it.
Either u make yourself a button or a movieclip with 4 frames and make it track as button. Then key in 2 more event listeners for this button for e.g.
MovieClipName/ButtonName.addEventListener(MouseEvent.MOUSE_OVER,MouseOverEffect);
function MouseOverEffect(evt:Event){
//MovieClip.gotoAndPlay(“EffectOn”);
}
MovieClipName/ButtonName.addEventListener(MouseEvent.MOUSE_OUT,MouseOffEffect);
function MouseOffEffect(evt:Event){
//MovieClip.gotoAndPlay(“EffectOFF”);
}
Hi All,
Can any one tell me how can I call the btn1 action on click btn2?
E.g. There are tow buttons on the stage named btn1 and btn2.
btn1.addEventListener(MouseEvent.CLICK, btn1_clicked)
function btn1_clicked(e:MouseEvent):void{
trace(‘you have clicked’);
}
btn2.addEventListener(MouseEvent.CLICK, btn2_clicked)
function btn2_clicked(e:MouseEvent):void{
//???? Here I want to call btn1 action. Can you tell me???????
}
Thanks,
Uday
uday_sgh@yahoo.com
are you trying to simulate a double click event? if it is there’s actually a special double click listener in MouseEvent.
if not event listener always listens to a MouseEvent obviously if btn1 is far away from your mouse to listen to the event onclick on btn2 when it is clicked. Just write a general function for btn2 and btn1
e.g.
btn1.addEventListener(MouseEvent.CLICK, btn1_clicked)
function btn1_clicked(e:MouseEvent):void{
traceFunc(’you have clicked’);
}
btn2.addEventListener(MouseEvent.CLICK, btn2_clicked)
function btn2_clicked(e:MouseEvent):void{
traceFunc(’you have clicked’);
}
Thanks Mr. Good Stuff for your quick reply.
In your reply that it not a correct answer as I asked.
My requirement was that I want call the action of btn1.
e.g.
btn1.addEventListener(MouseEvent.CLICK, btn1_clicked)
function btn1_clicked(e:MouseEvent):void{
traceFunc(’you have clicked’);
// Here can be a lot of code related to btn1
}
btn2.addEventListener(MouseEvent.CLICK, btn2_clicked)
function btn2_clicked(e:MouseEvent):void{
// Here I want all the funtionality of btn1
}
See in AS 2.0.
e.g.
btn1.onPress = function(){
traceFunc(’you have clicked’);
}
btn2.onPress = function(){
btn1.onPress();
}
So, I want only the above functionality in AS3.0.
Thanks,
Uday
uday_sgh@yahoo.com
Hi everybody, can somebody help me with hit test in game.
My code:
var counter:Number = 0;
var startX:Number;
var startY:Number;
speak_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
speak_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
live_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
live_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
play_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
play_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
cook_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
cook_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
drink_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
drink_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
listen_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
listen_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
wear_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
wear_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
learn_mc.addEventListener(MouseEvent.MOUSE_DOWN, pickUp);
learn_mc.addEventListener(MouseEvent.MOUSE_UP, dropIt);
function pickUp(event:MouseEvent):void {
event.target.startDrag(true);
reply_txt.text = “”;
event.target.parent.addChild(event.target);
startX = event.target.x;
startY = event.target.y;
}
function dropIt(event:MouseEvent):void {
event.target.stopDrag();
var myTargetName:String = “target” + event.target.name;
var myTarget:DisplayObject = getChildByName(myTargetName);
if (event.target.dropTarget != null && event.target.dropTarget.parent == myTarget){
reply_txt.text = “Good Job!”;
event.target.removeEventListener(MouseEvent.MOUSE_DOWN, pickUp);
event.target.removeEventListener(MouseEvent.MOUSE_UP, dropIt);
event.target.buttonMode = false;
event.target.x = myTarget.x;
event.target.y = myTarget.y;
counter++;
} else {
reply_txt.text = “Try Again!”;
event.target.x = startX;
event.target.y = startY;
}
if(counter == 8){ //pocet spravnych umiestneni
reply_txt.text = “Congrats, you’re finished!”;
}
}
speak_mc.buttonMode = true;
live_mc.buttonMode = true;
play_mc.buttonMode = true;
cook_mc.buttonMode = true;
drink_mc.buttonMode = true;
listen_mc.buttonMode = true;
wear_mc.buttonMode = true;
learn_mc.buttonMode = true;
I watch new tab that show points how many are correct and how many are incorrect.
Thanks
just place a hitTestObject check at the function dropIt
if ( event.target.hitTestObject(WhateverMovieClipUWannaHitTestWith)){ //which returns a true or false statement
trace(“There’s a correct hit!”)
}
Thanks Mr.
and if I want name individually items in order?
example:
if ( event.target.hitTestObject(cook_mc, speak_mc etc. …)){
trace(“There’s a correct hit!”)
- more items in the list (movie clips)
Thanks
I want to add check button with function that show new little window with results (correct and wrong points or answers). Function with counter of correct and incorrect answers.
Thanks
make a loop to traverse movieclip hit test area. But you have to rename your movieclip instance name so that you can traverse it like cook_mc1, cook_mc2, and etc
for (var i:int = 1; i < 5;i++){
if (event.target.hitTestObject ( this["cook_mc"+i] ) {
trace("cook_mc"+i+" : is hit");
}
}
I wrote this code:
for (var i:int = 1; i < 5;i++){
if ( event.target.hitTestObject(this["cook_mc, learn_mc, listen_mc, drink_mc, speak_mc"+i])){
trace("There’s a correct hit!")
}
}
but an error show me in output:
TypeError: Error #2007: Parametr hitTestObject cannot be null.
at flash.display::DisplayObject/_hitTest()
at flash.display::DisplayObject/hitTestObject()
at english_fla::presentsimple_10/dropIt()
I don know when I have to put this code – before or after function dropIt(event:MouseEvent):void {
event.target.stopDrag();
Thanks
Game:
There are some sentences and each sentence has empty space for correct word. You have to choose correct word and fill gap with word. For this purpose I use function DRAG AND DROP. Correct word are on the one side and sentences are on the other. If I drag and drop correct word count it and if I drag and drop incorrect word count it too. And at the end of the exercise I click CHECK button and new window show the answers/show points or something like that. But I want word will stay on the stage if the answer is incorrect – I wont the word comeback to the same position as the word was.
John _________ football every day.
words: swim, plays, draw ….
HI, I need help with this function:
function dropIt(event:MouseEvent):void {
event.target.stopDrag();
var myTargetName:String = “target” + event.target.name;
var myTarget:DisplayObject = getChildByName(myTargetName);
cook_mc.filters = [];
/*if (event.target.dropTarget.parent == myTarget){
event.target.x = myTarget.x;
event.target.y = myTarget.y;
}*/
if (event.target.dropTarget != null && event.target.dropTarget.parent == myTarget){
reply_txt.text = “Good Job!”;
event.target.removeEventListener(MouseEvent.MOUSE_DOWN, pickUp);
event.target.removeEventListener(MouseEvent.MOUSE_UP, dropIt);
event.target.buttonMode = false;
event.target.x = myTarget.x;
event.target.y = myTarget.y;
Insted of getChildByName(myTargetName) – I need whatever
additional concrete names, for example (targetspeak_mc, targetlive_mc, targetplay_mc). Create more concrete targets for function drag and drop.
Is there a code to drag from the orginal box as many copies on the stage as i want?
to kYnTs, yeah just addchild(same variable) everytime you perform a click on the target
Hi, I would like to ask how to do this in flash:
I want to make a custom designing shirt in flash. Instead of dragging colors on the shirt, i will need to use the actual fabric pattern (in .png or ,jpg format). So how to do that? Please help. Thanks.
Useful information. Fortunate me I discovered your website accidentally, and I’m surprised why this accident did not happened in advance! I bookmarked it.
Hi everybody, can somebody help me with hit test in example
i want to make tests as following:
in the first page I put Drag&Drop test for ordering a sentence,
when the answer is correct I want the test to go next question (next frame)..etc
this is my code
package
{
import flash.events.*;
import flash.display.*;
public class Map extends MovieClip
{
var dragdrops:Array;
public function Map()
{
// constructor code
dragdrops = [Go,Going,Did,Are,About,Send,You,]
var currentObject:DragDrop;
for (var i:uint = 0; i <dragdrops.length; i++)
{
currentObject = dragdrops[i];
currentObject.target = getChildByName(currentObject.name + "_tar");
}
}
public function match():void
{
}
//numOfMatches=0;//
//addChild(win);//
}
}
and as dragdrop
package
{
import flash.events.*;
import flash.display.*;
public class DragDrop extends Sprite
{
var origx = Number;
var origy = Number;
var target = DisplayObject;
public function DragDrop()
{
origx = x;
origy = y;
// constructor code
addEventListener(MouseEvent.MOUSE_DOWN,drag);
}
function drag (e:MouseEvent):void
{
stage.addEventListener(MouseEvent.MOUSE_UP,drop)
startDrag();
parent.addChild(this);
}
function drop (e:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_UP,drop)
stopDrag();
if (hitTestObject(target))
{
visible = false
target.alpha = 1;
//Object(parent).match();//
Object(parent).match();
}
x = origx;
y = origy;
}
}
}
use a enterFrame listener to check the events of dragdrop success. If any of the box is dragged correctly. Snap the movieclip (disable it’s drag functionality) and add a score counter e.g. CorrectHit++
stage.addEvenListener(Event.ENTER_FRAME, checkDragDropChecker );
function checkDragDropChecker {
if (CorrectHit >= 7){
funcGoNextFrame();
}
}