0

I have the following code which navigates between elements using the left and right arrow keys.

$(document).keydown(function (event) { 

    if (event.keyCode === 37) { 
        console.log("left")
        currentPosition > 0 ? currentPosition-- : maxFocusablePosition; 
    } 

    if (event.keyCode === 39) { 
        console.log("right")
        currentPosition < maxFocusablePosition ? currentPosition++ : 0; 
    } 

I tried implementing the following, but it doesnt work:

if ( event.ctrlKey && ( event.which === 37 ) ) {
    console.log( "Combo Move" );
}
Kode_12
  • 4,506
  • 11
  • 47
  • 97
  • Possible duplicate of [javascript multiple keys pressed at once](http://stackoverflow.com/questions/5203407/javascript-multiple-keys-pressed-at-once) – Evan Davis Mar 10 '16 at 16:41

2 Answers2

0

Really? I am surprised because ctrlKey and which work for me!

The keyboard event API is a disgrace. The W3C has been dragging their feet for a long time regarding the standardization of keyboard events. This is why you may see a lot of conflicting information.

$(function() {
  var input = $('input');
  input.on('keydown', function(event) {
    if (event.which === 37 && event.ctrlKey) {
      input.val('ctrl-left');
    } else if (event.which === 39 && event.ctrlKey) {
      input.val('ctrl-right');
    } else {
      input.val('');
    }
  });
  input.focus();
});
input { width: 100%; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Press Ctrl-left or Ctrl-right in here">
doug65536
  • 6,562
  • 3
  • 43
  • 53
-1

Use keyCode as below and use in the function.

$(document).keydown(function (event) { 

    var keyCode = event.keyCode || event.which;

    if (keyCode === 37) { 
        console.log("left")
        currentPosition > 0 ? currentPosition-- : maxFocusablePosition; 
    } 

    if (keyCode === 39) { 
        console.log("right")
        currentPosition < maxFocusablePosition ? currentPosition++ : 0; 
    } 

    if ( event.ctrlKey && ( keyCode === 37 ) ) {
        console.log( "Combo Move" );
    }
Prasanna Rkv
  • 419
  • 4
  • 12