Home > Software engineering >  Get the keyboard button pressed during onClick and based on that run different functions
Get the keyboard button pressed during onClick and based on that run different functions

Time:11-06

Currently, I have 9 different functions which has to triggered by single button when onclick and keyboard numpad (1 to 9).

Edit: Solution by Sode- v2

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>

<button type="button" id="b41" onclick="test_ks(event)">Shape Anchor Point</button>

 <script>


  const pressedButtons = {};

  window.onkeydown = (e) => (pressedButtons[e.which] = true);
  window.onkeyup = (e) => (pressedButtons[e.which] = false);

  function test_ks(event) {
    
    if (pressedButtons[97]) {
      alert('numpad 1');
    } else if (pressedButtons[98]) {
      alert('numpad 2');
    }
  }
  
</script>

</body>
</html>


  

Tried this at https://manjunath7472.w3spaces.com/saved-from-Tryit-2021-11-06.html

Issue 1.After clicking numberpad 1, numberpad 2 doesn't work & After clicking numpad2, numpad1 works but after that numpad 2 doesn't work.

2.After initial click on anyone, from second time, with just mouse click(without pressing keyboard numpad) it triggers the alert.

3.After first clcik with keypress, it doesn't consider keyboard press and alert is triggered by mouse click only.

CodePudding user response:

When you bind a function to onclick in the HTML tag you want to just pass the name of the function as the event parameter will be passed in by the DOM

<button type="button" id="b41" onclick="myFunction()">myButtonName</button>

but also, a button's click event won't have any keyboard data attached to it, so you may want to look into using keydown and keyup event listeners (probably on the window object) to keep track of which keys are pressed and using that information when the button is clicked

<button type="button" id="b41" onclick="myFunction()">myButtonName</button>
<span id="output"></span>

<script>
  const pressedButtons = {};

  const outputSpan = document.querySelector('#output');

  window.onkeydown = (e) => (pressedButtons[e.which] = true);
  window.onkeyup = (e) => (pressedButtons[e.which] = false);

  function myFunction(event) {
    console.log(pressedButtons);
    if (pressedButtons[97]) {
      outputSpan.innerHTML = 'numpad 1';
    } else if (pressedButtons[98]) {
      outputSpan.innerHTML = 'numpad 2';
    } else {
      outputSpan.innerHTML = '';
    }
  }
</script>

Edit: updated to change text of a span rather than use alert()

  • Related