Home > front end >  Prevent keypress event listener from being triggered while bootstrap modal is open
Prevent keypress event listener from being triggered while bootstrap modal is open

Time:11-17

I have a web app built using node, express, and ejs as the view engine. On a specific page I have an event listener that will go to the home page on key press, like so:

<script>
  document.addEventListener("keypress", function onPress(event) {
    window.location = ('/home');
  });

</script>

The issue is that I also have a button on that page that when pressed displays a bootstrap Modal element that includes input for text, so when the modal is open and the user tries to enter some input the event listener is triggered. Is there a way to ignore this event listener until the modal is closed?

I have tried giving a DOM (not containing the modal) a tabindex to make it selectable and putting the event listener on that, but then the user has to click on the page before the event listener can be triggered which is not ideal

CodePudding user response:

The best way here would be to track the modalOpenState in a boolean variable. When the modal opens, set it to true, and false when closed. And when you're listening for the keypress event, check if the modalOpenState is true or false, and then redirect accordingly.

Note: As Zameer's comment also states, 'keypress' event is deprecated and can stop working any time. MDN suggests replacing it with beforeinput or keydown event as per requirement.

CodePudding user response:

You can prevent the event in input from propagating up towards to the document by using event.stopPropagation and then user input won't trigger the document keypress listener.

document.addEventListener("keypress", function (event) {
  console.log("event", event);
  console.log("keyPress");
});

const input = document.getElementById("user-input");
input.addEventListener("keypress", function (e) {
  e.stopPropagation(); 
});

const btn = document.getElementById("hello-btn");
btn.addEventListener("click", function onClick(e) {
  console.log("clicked btn");
});
<!DOCTYPE html>
<html>
  <head>
    <title>Sample</title>
    <meta charset="UTF-8" />
  </head>

  <body>
    <div id="app">
      <button id="hello-btn">Say hello</button>
      <input id="user-input" placeholder="enter text" />
    </div>
    <script src="src/index.js"></script>
  </body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

However, I would suggest not to attach the keypress event on document. As per MDN it's deprecated: https://developer.mozilla.org/en-US/docs/Web/API/Document/keypress_event#browser_compatibility.

  • Related