Wednesday, October 8, 2014

Run javascript function on arrow keys when press

The function triggers when we press any keys on our keyboard. for example in our function left(), when we click our keyboards left button the div #result will change its html. see live demo for clarification.
 function left() {
  $('.result').html('left');
 }

 function right() {
  $('.result').html('right');
 }
 function up() {
  $('.result').html('up');
 }
 function down() {
  $('.result').html('down');
 }

 document.onkeydown = function(evt) {
  evt = evt || window.event;
  switch (evt.keyCode) {
   case 39:
    left();
    break;
   case 37:
    right();
    break;
   case 38:
    up();
    break;
   case 40:
    down();
    break;                    
  }
 };

Live Demo

No comments:

Post a Comment