0

I'm trying to get a response for when visitor uses the keys right and left

<script>
  $(document).keypress(function(event) {
    key = String.fromCharCode(event.which)
    if(key == '37' || key == '39') {
      $('main').html('You pressed : ' + key)
      event.preventDefault()
    }
  });
</script>

It's not working. what did work was the line

if(key == 'a')

I used this table to find the code https://www.cambiaresearch.com/articles/15/javascript-char-codes-key-codes

Is it because jQuery has different table? or maybe I should load JavaScript as well? then how do I do use the two of them? (jQuery and JavaScript?)?

EDIT:

I think I got it

String.fromCharCode(event.which)

JavaScript can't read strings as numbers? do I need to use different function? I'm new to this can you tell me what to do?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Roai1
  • 11
  • 2

2 Answers2

0

I find for myself that when I go to implement these sorts of "get item from event", that a simple console.log(event) does wonders. I'd start with:

$('body').on('keypress', function(evt){
    console.log('Event: ', evt);
});

Then, press the right and left arrow keys and see what happens.

First, an observation: I note that you're comparing the string '37', which is distinct from the integer value 37. The former is two or four bytes (depending on how the JS implementation stores characters), while the latter is one byte. Is that your intention after reading the appropriate APIs?

Second, as a specific suggestion, if you're using jQuery, take advantage of it's normalization routines. In this case, event.which is returning 0, but you can use event.keyCode which is probably what you want to compare:

if ( 37 === event.keyCode ) {
  // ...
}
else if ( 39 === event.keyCode ) {
  // ....
}
hunteke
  • 3,648
  • 1
  • 7
  • 17
  • Thanks a lot! i tried to upvote but it does'nt let me. can you help me with using jquery with changing background? i tried this if(event.keyCode == 37 || event.keyCode == 39) { $('main').css('background ','yellow') event.preventDefault() } }) but it does'nt work – Roai1 Oct 12 '17 at 03:45
  • Unfortunately, without more context, no. Suggest you read the jQuery API, and/or post a new question. This question has been answered. – hunteke Oct 12 '17 at 03:55
  • I think you're supposed to submit another question for follow-ups like this, but to help you out, you can look at [this question](https://stackoverflow.com/questions/4283141/jquery-change-background-color) – Garrett Oct 12 '17 at 03:55
0

What you want to use is the keydown event. Also, no reason to use the String.fromCharCode, you can just compare the integers. Something like this would work

$(document).keydown(function(event) {
  if (event.which == 37 || event.which == 39) {
    var key = event.which == 37 ? 'left' : 'right';
    $('main').html('You pressed : ' + key)
    event.preventDefault()
  }
})
Garrett
  • 106
  • 5