javascript - Keybinding a button that triggers its onclick function -


i left , right arrow keys trigger , next button clicks in javascript. feel i'm not quite implementing correctly since buttons work keystrokes 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();             }         });      } 

you want 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 event listener style you'd want (native dom versus jquery) because you've got mix, should pointed in right direction.


from experience, if have more simple use case handling keypresses, i'd recommend utilizing library, keypress.


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -