-2

So the problem is... It doesn't work. And more correctly... how can i better execute those nested ifs?

document.body.onkeypress = function(e) {

                e = e || window.event;

                if (e.keyCode == '38') { //arrow up

                }
                if (e.keyCode == '40') { //arrow down
                    if (top == 1) {
                        window.setTimeout(show2, 100);
                        alert('2 layer works');
                    }
                    if (top == 2) {
                        window.setTimeout(show3, 100);
                    }
                    if (top == 3) {
                        window.setTimeout(show4, 100);
                    }
                }

            }

I've tried everything. Please help me...

FalsePride
  • 53
  • 3
  • 12

2 Answers2

0

Start with this example. It shows how to hook up the keydown event to the document body correctly. From here you should be able to modify it to add the additional logic you have in your example. Be careful to make sure external variables like top are set correctly.

function handleKeyDown(e) {
  console.log('got keyDown event.  e.keyCode =', e.keyCode)
}

document.body.addEventListener("keydown", handleKeyDown, false);
<p>Press a key</p>
Wyck
  • 10,311
  • 6
  • 39
  • 60
  • 1
    It might also be worth noting that `e.keyCode` is deprecated, and it's recommended to use `e.key` now. See [keypress event](https://developer.mozilla.org/en-US/docs/Web/Events/keypress) – Herohtar Oct 15 '18 at 18:24
0

Where do you change the top value...? Also the first if statement, if its blank like you showed us here, will throw in an error, or at least won't do anything. Why do you say e = e || window.event ..? Also, this might be just me, but don't call the functions like that. Better ( again, at least in my opinion ) to do:

document.body.addEventListener("keypress", e => {
// Get rid of that e = e || window.event, I have no clue why you'd do that.
if (e.keyCode == 38) {
 // Actually give it some parameters to do here, leaving it empty will either 
 // throw an error or in "best" case won't do anything.
}
if (e.keyCode == 40) {
               // Again, you said you did var top = 1. It will work here.
                if (top == 1) {
                    window.setTimeout(show2, 100);
                    alert('2 layer works');
                }
               // But you dont INCREMENT the top variable anywhere, so this wont work.
                if (top == 2) {
                    window.setTimeout(show3, 100);
                }
                // But you dont INCREMENT the top variable anywhere, so this wont work.
                if (top == 3) {
                    window.setTimeout(show4, 100);
                }
  }

})

This question is really, really badly formatted and you haven't provided much information. Show us the error you get, use console.log all the time, it's your best friend.

Petar
  • 539
  • 5
  • 14