Javascript add an event listener anytime and remove an event listener anytime

  • On the webpage, I have a button when I click, it calls the JavaScript function.
  • In this function, I show a modal dialog box, and I want to handle keystrokes only at this time. That is, when the modal dialogue is visible.
  • When I close the modal dialog, I want to stop the keystroke processing.

  • consider that I press the button and the sam () function is called.

    function sam () {document.onkeypress = function (e) {processKeystroke (e); }}

  • So, now the function is tied to a keypress event. when a key is ever pressed, the processkeystroke function will be called. The sam function is called only after the modal dialog box is displayed.

  • Now I close the modal dialog and with this I do not want the function (e) {processKes ...} to be called.

  • What do I need to do to remove the connected event listener from the document. unkeypress.

  • Also, I would like to have alternatives for the above approach, because the one I took from myself and I did not refer to any specific documentation, so I really look through the trial and error procedure for using event handlers or listeners.

  • Therefore, when I call the sam function, I want the function to be bound to the key press event, and if I call another example of the form form closedialog (), I want the key listen function to be removed. Because I want to write the correct code, which should not consume a lot of system resources.

+3
1

, .

 document.onkeypress = null;

, , jquery, bind (attach) unbind ( detach) , keypress.

+2

Source: https://habr.com/ru/post/1762818/


All Articles