Skip to main content
jduncan
Community Expert
Community Expert
July 12, 2022
Answered

keydown EventListener Firing Twice For Some Keys

  • July 12, 2022
  • 1 reply
  • 3717 views

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();

 

This topic has been closed for replies.
Correct answer m1b

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();
    }
});

 

1 reply

m1b
Community Expert
m1bCommunity ExpertCorrect answer
Community Expert
July 12, 2022

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();
    }
});

 

jduncan
Community Expert
jduncanCommunity ExpertAuthor
Community Expert
July 12, 2022

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!

CarlosCanto
Community Expert
Community Expert
July 13, 2022

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()