Copy link to clipboard
Copied
Hello, a submit button is on the stage next to a text input field. It must be possible to use both mouse and the enter key to press the button.
What's the fastest and easiest way to add an eventListener to the ENTER key, on the button?
cast it:
function handler(event:Event){
if((event is KeyboarEvent && KeyboardEvent(event).charCode == 13) || event.currentTarget == submitBtn)
{}
}
Copy link to clipboard
Copied
add a keyboard event listener to the stage and mouseevent listener to your submit button. They can both call the same listener function (use Event for the argument type).
Copy link to clipboard
Copied
So it would have to be something like this? But now the MouseEvent won't work? Do I really have to create a duplicate of the function for both to work? Seems like a hassle..
submitBtn.addEventListener(MouseEvent.CLICK,handler);
stage.addEventListener(KeyboardEvent.KEY_DOWN,handler);
function handler(Event){
if(event.charCode == 13)
{}
}
Copy link to clipboard
Copied
You should be able to expand the conditional in the one function to handle both cases using an OR (||), as in...
function handler(event:Event){
if(event.charCode == 13 || event.currentTarget == submitBtn)
{}
}
Edit: repaired = to be ==
Copy link to clipboard
Copied
I worked pretty well, but it's giving me a dilemma problem.. I can't define the event-type (in the function) to evt:Event, because the keyCode then becomes an "undefined property". However if I change the event-type to evt:KeyboardEvent - keyCodeworks, but then the MouseEvent "on the other side" don't.
No compiler errors occur though, just in the output tab it says Error #1034, cannot convert MouseEvent to KeyboardEvent - every time I try to hit the sumbitBtn on the stage.
Note: I want to upload the code, but it's on a work-computer without internet nor the possibility to connect a usb-stick or anything...
Copy link to clipboard
Copied
cast it:
function handler(event:Event){
if((event is KeyboarEvent && KeyboardEvent(event).charCode == 13) || event.currentTarget == submitBtn)
{}
}
Copy link to clipboard
Copied
That worked very well! Thanks for helping!
On another subject, event is KeyboarEvent is new to me. I couldn't find any good explanations for it, on the web. Care to explain in short terms?
Ex.: It seems like it's converting the event definition. Therefore why not convert it back on the other side of the logical OR operator?
Copy link to clipboard
Copied
It is not converting it, it is testing it.
Copy link to clipboard
Copied
The fastest and easiest way to add a listener is to copy and paste the code. You can make the Enter key perform the same actions as pressing the button but you cannot make the Enter key press the button (The Enter key cannot hover over the button either).
Find more inspiration, events, and resources on the new Adobe Community
Explore Now