1

event on keypress arrows down not working, not changing color to red, no errors at console, What i'm doing wrong?

 var getText = document.getElementsByTagName('h1')[0];

            getText.onclick = function() {
                    getText.innerHTML = "Simple";
            }

              function keyPress() {
                if(event.which == 13) { 
                    getText.style.color = 'blue';
                }

                if(event.which == 40) {
                    getText.style.color = 'red';
                }
            }
Cyril Cherian
  • 32,177
  • 7
  • 46
  • 55
Viktor
  • 722
  • 1
  • 8
  • 25
  • 3
    Your code is missing some part... Where does the `event` variable gets set? I don't see you listening to the keypress event either. – Salketer Oct 07 '15 at 07:58
  • Also, arrow keys are usually not triggering the keypress event... But I'll give more details about all this once I see your real case. – Salketer Oct 07 '15 at 07:59

1 Answers1

1

As @Salketer noted you need an event listener to observe keyboard events. The keyPress function could be used as event handler in that case. (But event must be set as the first argument in the function definition.)

var getText = document.getElementsByTagName( 'h1' )[0];

function keyPress( event ) {
    if(event.which == 13) { 
        getText.style.color = 'blue';
    }

    if(event.which == 40) {
        getText.style.color = 'red';
    }
}

/* Setup an event listener and use keyPress as event handler */
window.addEventListener( 'keydown', keyPress, false );

See: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

Andy E
  • 338,112
  • 86
  • 474
  • 445
feeela
  • 29,399
  • 7
  • 59
  • 71