Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Up And Down Keys

Regy

Active Coder
I am trying to navigate a list using the up and down keys. And when the up or down key is pressed, information about the highlighted item should be shown to the user. The code examples I've found aren't clear to me or don't address my problem. This is the best code I can find (that I sort of understand):
JavaScript:
document.addEventListener('keydown', function(event) {
        if(event.code == 'KeyZ' && (event.ctrlKey || event.metaKey)) {
          alert('Undo')
        }
      })
But this code is not linked to my list. And I can't work out how to do that. Here is my HTML:
HTML:
<div id="mylist">
<select id="myitems" size="5" onclick="GetSelectedText()">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
</select>
</div>
I am completely new to javascript and I was hoping someone could help me out with this problem because I'm out of ideas. Thanks for any help!
 
Thanks Carl. I have two questions...
What do you mean by "listen to the window rather than the document"?
What exactly should I be looking at in that StackOverflow page?
 
Because your code is "listening" for up/down keys, the focus on your webpage might not be on document.addEventListener which is why nothing happens.

On the stackoverflow page it's discussing how and where to listen for certain keys, therefore, you may need to change your javascript to do the window.event rather than document.addEventListener and move the code there, when a specific key has been pressed.
 
Having re-read that document, how about trying:-

Code:
document.onkeydown('keydown', function(event) {
        if(event.code == 'KeyZ' && (event.ctrlKey || event.metaKey)) {
          alert('Undo')
        }
      })
 
My apologies Carl, I seem to have led you down the wrong path. Today I came across a line of code like this:
HTML:
onkeyup="dosomething()"
That's when I realized my mistake. I was so caught up in Javascript that I thought I had to identify the list using Javascript. So the solution is:
HTML:
<select id="myitems" size="5" onclick="GetSelectedText()" onkeyup="dosomething()">
JavaScript:
function dosomething(){
    if (event.code == 'ArrowUp'){
    alert("Arrow Up");}
    else if (event.code == "ArrowDown"){
    alert("Arrow Down");
    }
}
But then I run into another problem because Visual Studio Code says that "event" is deprecated. So do you know how I fix this? It may have something to do with the empty brackets after "dosomething" I'll try and find a solution but if you have any answers that would be good of you.

Thanks again for your help Carl.

Oh and one other thing, should it be "event.code" or "event.key"?

Thank you!
 
Does this help any:-

[CODE title="HTML"]<div id="mylist">
<select id="myitems" size="5" onclick="GetSelectedText(value)">
<option value="1" label="Item 1"></option>
<option value="2" label="Item 2"</option>
</select>
</div>[/CODE]

[CODE title="Javascript"]
const log = document.getElementById('myitems');

log.addEventListener('keyup', logKey);

function logKey(e) {
console.log(e.keyCode);

if (e.keyCode == 38) {
console.log('Up Key Pressed');
console.log('Value is now - ' + document.getElementById("myitems").value);
}
if (e.keyCode == 40) {
console.log('Down Key Pressed');
console.log('Value is now - ' + document.getElementById("myitems").value);
}
}

function GetSelectedText(value) {
console.log(value);
}
[/CODE]

Amended the code to only listen to the select item!

Regards
Carl
 
Hi (again)

Ok, check these changes:-

[CODE title="HTML"]<div id="mylist">
<select id="myitems" size="5" onclick="GetSelectedText(value)">
<option value="1">Item 1</option>
<option value="2">Item 2</option>
</select>
</div>[/CODE]


[CODE title="Javascript"]const log = document.getElementById('myitems');

log.addEventListener('keyup', logKey);

function logKey(e) {
console.log(e.keyCode);

if (e.keyCode == 38) {
console.log('Up Key Pressed');
console.log('Value is now - ' + log.value);
console.log('Label is now - ' + log.options[log.value - 1].text);
}
if (e.keyCode == 40) {
console.log('Down Key Pressed');
console.log('Value is now - ' + log.value);
console.log('Label is now - ' + log.options[log.value - 1].text);
}
}

function GetSelectedText(value) {
console.log(value);
console.log('Value is now - ' + value);
console.log('Label is now - ' + log.options[value - 1].text);
}[/CODE]
 
Thanks for trying Carl but I got some errors with your code while testing it using MS Edge. Now I'm not on my testing computer at the moment so this is what I can remember about the errors. The first error was with this code:
JavaScript:
log.addEventListener('keyup', logKey);
MS Edge said something like "Can't read the code/null error". And there was also an error with this code:
JavaScript:
console.log('Label is now - ' + log.options[value - 1].text);
This error message had something to do with the "options" word if I remember correctly. I do remember that it wasn't showing the "Label" information in the console. And I tried changing your code but I came up with nothing. So perhaps there's another way of solving this problem?
 
As far as I can tell this code works.

HTML:
<select id="mylist" size="5" onclick="GetSelectedText()" onkeyup="dosomething(event)">

JavaScript:
function dosomething(event){
var e = document.getElementById("mylist");
var result = e.options[e.selectedIndex].text;

if (event.code == 'ArrowUp'){
    alert("Arrow Up");}
    else if (event.code == "ArrowDown"){
    alert("Arrow Down");
    }
}

While I was trying to solve my problem I went back to your code Carl and I noticed that you used "value" in this line of code:

HTML:
onclick="GetSelectedText(value)"

That got me thinking about the website I mentioned before, the one that said the VS Code error had something to do with empty brackets. So I went back to that website and took a closer look and found out that I needed to use "event". Then I thought maybe if I put "event" in my function code and my HTML code it might work. And it did :)

Now VS Code doesn't tell me that "event" is deprecated (another example of an IDE giving out incorrect error information?). I also know that I can use event.code in my code. And it works in MS Edge and Safari.

So Carl thanks for your code (and other information) as it did help in the end and thanks especially for spending time trying to help me.
 

Buy us a coffee!

Back
Top Bottom