3

In my app I need to handle Alt key press/release to toggle additional information on tooltips. However, the first time Alt is pressed, document loses keyboard focus, because it goes to Chrome's menu. If I click any part of the document, it works again (once).

I can avoid this by calling preventDefault, but that also disables keyboard shortcuts such as Alt+Left/Right, which is undesirable.

I can also handle mousemove and check altKey flag, but it looks very awkward when things only update when mouse is moved.

Is there any way to reliably detect current Alt key state in my situation? I would really rather not switch to a different key.

Update: I suppose the best solution would be to call preventDefault only when a tooltip is active.

  document.addEventListener("keydown", (e) => {
    if (this.curComponent) e.preventDefault();
    if (e.which === 18) {
      this.outer.classList.add("AltKey");
    }
  });
  document.addEventListener("keyup", (e) => {
    if (this.curComponent) e.preventDefault();
    if (e.which === 18) {
      this.outer.classList.remove("AltKey");
    }
  });
riv
  • 6,846
  • 2
  • 34
  • 63

2 Answers2

2

I had the same issue and I solved thanks to this answer:

document.addEventListener("keyup", (e) => {
    if (e.key === "Alt") {
        return true; // Instead of e.preventDefault();
    });

return true restores normal behavior of Alt+Left/Right chrome keyboard shortcuts.

jcastrov
  • 68
  • 2
  • 9
0

Keyboard value both left/ right side ALT = 18

jQuery:

$(document).keyup(function(e){
    if(e.which == 18){
      alert("Alt key press");
    }
});

JavaScript

document.keyup = function(e){
  if(e.which == 18){
    alert("Alt key press");
  }
}
Mahfuzur Rahman
  • 1,497
  • 18
  • 23
  • I know how to set the event, but it doesn't work. Please read the question. Also, 17 is Ctrl, not Alt. – riv Dec 12 '17 at 20:57