0

The code snippet provided will Pop Up Alert when Backspace and Delete Key is Pressed on Keyboard with the cursor clicked on the textbox. However, now I want to implement it in my codepen demo here, but I am unsure on how to do it. I want the alert box to pop up only when the cursor is placed on the grey box only if the Backspace and Delete Key is Pressed. I will really appreciate any help I can get.

Click on Text Box and Press on Delete and Backspace for Pop UP
<br>
<input id="input">

<script>
var myinput = document.getElementById('main-container');
input.onkeydown = function() {
  if (event.keyCode == 8) {
    alert('you pressed backspace');
    //event.preventDefault();
  }

  if (event.keyCode == 46) {
    alert('you pressed delete');
    //event.preventDefault();
  }
};

</script>

I have tried var myinput = document.getElementById('zoomPanCont'); , which is the div id but it does not work unfortunately.

1 Answers1

0

I don't have enough reputation to comment, but does stackoverflow.com/a/48868196 answer your question? You just need to add the tabindex attribute to the div

grimsteel
  • 796
  • 1
  • 17
  • Hi, thank you for your link. I have copied an example from the link to be tested out at https://codepen.io/Maximusssssu/pen/xxajQZb?editors=1011, but it uses 'keydown', which means any key can trigger it, may I ask how do I do with just the delete key and not any other key to trigger it? Thank you :) – Jimmy Brown Mar 16 '23 at 01:43
  • So, I believe I must assign it by ClassName and Not ID right for it to work? – Jimmy Brown Mar 16 '23 at 01:44
  • @Jimmy Brown No, the issue was that the div element isn't selectable. Add `tabindex="0"` to the div and then your original code should work – grimsteel Mar 16 '23 at 01:47