cosmichero 2025 cosmichero 2025 - 7 months ago 24
Javascript Question

Keybinding a button that triggers its onclick function

I would like the left and right arrow keys to trigger the back and next button clicks in my Javascript. I feel like I'm not quite implementing it correctly since my buttons work but the keystrokes do not.

function init() {
flashmovie = document.getElementById('flashmovie');
document.getElementById('back').onclick = function () {
if (c == 0) {
c = paths.length;
}
c--
displayFiles();
}

document.getElementById('next').onclick = function () {
if (c == paths.length - 1) {
c = -1;
}
c++;
displayFiles();
}

document.keypress(function (e) {
if (e.which == 37) {
$("#back").click();
}
});

document.keypress(function (e) {
if (e.which == 39) {
$("#next").click();
}
});

}

Answer

You probably want the keydown event.

function init() {
  document.getElementById('back').onclick = function() {
    console.log('back!');
  }

  document.getElementById('next').onclick = function() {
    console.log('next!');
  }

  document.addEventListener('keydown', function(e) {
    if (e.which == 37) {
      $("#back").click();
    }
  });

  document.addEventListener('keydown', function(e) {
    if (e.which === 39) {
      $("#next").click();
    }
  });
}

init();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="back">Back</button>
<button id="next">Next</button>

I guessed which event listener style you'd want (native DOM versus jQuery) because you've got a mix, but this should get you pointed in the right direction.


From experience, if you have more than a very simple use case for handling keypresses, I'd recommend utilizing a library, like Keypress.