Copy link to clipboard
Copied
Hey, any idea why the "keydown" event listener would be firing twice for certain keys (e.g. arrow key). I'm trying to adjust the listbox selection with the up and down arrow keys while inside the edittext box. Everything works but it fires twice and moves the selection down two spots.
Example code below... Thanks for any help!
// setup the dialog
var arr = ["Option 1", "Option 2", "Option 3", "Option 4", "Option 5", "Option 6"];
var win = new Window("dialog");
var text = win.add("edittext");
text.active = true;
var list = win.add("listbox", undefined, arr);
list.selection = 0;
// move list selection with arrow keys while in edittext
text.addEventListener("keydown", function (k) {
alert("Pressed Key: " + k.keyName);
if (k.keyName == "Up") {
list.selection = list.selection.index - 1;
} else if (k.keyName == "Down") {
list.selection = list.selection.index + 1;
}
});
win.show();
Hi @jduncan, I'm not sure why it fires twice, but you can fix it by adding "k.preventDefault();" into your listener.
- Mark
Edit: to clarify—don't preventDefault on all keydown events, just the ones you are targetting:
w.addEventListener("keydown", function (k) {
if (k.keyName == "Up") {
listbox.selection = listbox.selection.index - 1;
k.preventDefault();
} else if (k.keyName == "Down") {
listbox.selection = listbox.selection.index + 1;
k.preventDefault(
...
Copy link to clipboard
Copied
Hi @jduncan, I'm not sure why it fires twice, but you can fix it by adding "k.preventDefault();" into your listener.
- Mark
Edit: to clarify—don't preventDefault on all keydown events, just the ones you are targetting:
w.addEventListener("keydown", function (k) {
if (k.keyName == "Up") {
listbox.selection = listbox.selection.index - 1;
k.preventDefault();
} else if (k.keyName == "Down") {
listbox.selection = listbox.selection.index + 1;
k.preventDefault();
}
});
Copy link to clipboard
Copied
Yep, that's exactly what I used as a workaround, I was just curious if anyone knew why it fired twice.
And, I learned the hard way that I shouldn't preventDefault() all of the keys #facepalm!
Thanks so much for your help!
Copy link to clipboard
Copied
are you guys on mac? I'm on windows and the original script works just fine. up/down keys move one spot at a time without preventDefault()
Copy link to clipboard
Copied
Yeah I'm on Mac and I get the double-firing.
Copy link to clipboard
Copied
Hey @CarlosCanto, does it break on Windows when you add the preventDefault ?
Copy link to clipboard
Copied
Hi Mark, no it doesn't break after adding preventDefault().
Copy link to clipboard
Copied
...however, using preventDefault() helps by stopping the cursor from moving left/right, which is the default behaviour when pressing up/down keys while in the text box
Copy link to clipboard
Copied
Yep, I'm on a Mac as well.