cosmichero2025
cosmichero2025

Reputation: 1029

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();
            }
        });

    }

Upvotes: 1

Views: 1073

Answers (2)

jdphenix
jdphenix

Reputation: 15445

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.

Upvotes: 1

J.Cheong
J.Cheong

Reputation: 227

Without jquery, try this

document.onkeyup = function(e){
    if (e.which == 37) {
        $('#back').click();
    } else if (e.which == 39) {
        $('#next').click();
    }
}

With jquery,

$(document).keypress(function(e){
    if (e.which == 37) {
        $('#back').click();
    } else if (e.which == 39) {
        $('#next').click();
    }
});

Upvotes: 1

Related Questions