Vasko Pulkovski
Vasko Pulkovski

Reputation: 11

HTML button act like key pressed from keyboard, and function on certain object or entire website

The button should act like: Enter, Arrow Keys, Space ... Already tried some examples. Here's one:

var e = $.Event("keydown", { keyCode: 8});
$("#target").keypress();

Upvotes: 0

Views: 3423

Answers (1)

Andrew Mairose
Andrew Mairose

Reputation: 10985

First off, the keypress event is not triggered for non-printing keys, so the arrow keys will not work with .keypress().

From the jQuery documentation:

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser.

Instead, you would want to use .keydown() or .keyup(). But, instead of trying to trigger a keydown or keyup event when your button is clicked, why not just write a function that does what you want and call that function whenever the key is pressed or your button is clicked?

For example, say you want a character to move left when you push the left key or your left key button, you could write this function:

var moveLeft = function() {
   alert('Moving character left one position');
};

Then, you can call that function whenever the left key is pressed or your left button is clicked.

$('#left-btn').click(moveLeft);

$('body').keydown(function(e) {
    if (e.keyCode == 37) {
        moveLeft();
    }
});

Working example:

Inspect your browser's JavaScript console when clicking the left or right buttons or pressing the left or right arrow keys.

$(document).ready(function() {
  var moveLeft = function() {
    console.log('Moving left!');
  };

  var moveRight = function() {
    console.log('Moving right!');
  };

  $('body').keydown(function(e) {
    switch (e.keyCode) {
      case 37:
        moveLeft();
        break;
      case 39:
        moveRight();
        break;
    }
  });
  
  $('#left-btn').click(moveLeft);
  
  $('#right-btn').click(moveRight);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <button id="left-btn">&larr;</button>
  <button id="right-btn">&rarr;</button>
</div>

Upvotes: 1

Related Questions