Jayapal Chandran
Jayapal Chandran

Reputation: 11140

JavaScript add an event listener any time and remove the event listener any time

  1. In a web page I have a button when clicked it calls a JavaScript function.

  2. In that function I show a modal dialog box and I want to process keystrokes only at this time. That is when the modal dialog is visible.

  3. When I close the modal dialog I want to stop the keystroke processing.

  4. consider that I click a button and function sam() is called.

    function sam()
     {
      document.onkeypress = function(e) { processKeystroke(e); }
     }
    
  5. So now a function is attached to the keypress event. Whenever a key is pressed the function processkeystroke will be called. The function sam is called only after I display the modal dialog box.

  6. Now I am closing the modal dialog and with that I don't want function(e) { processKes...} to be called.

  7. What should I do to remove the attached event listener from document.onkeypress.

  8. Also I would like to have alternatives for the above approach because that one I assumed of my own and I did not refer any specific documentation, so I am really going through trial and error procedure to use event handlers or listeners.

  9. So when I call function sam I want a function to be attached with the keypress event and if I call another function form example closedialog() I want that keypress listening function to be removed. Because I want to write proper code which should not consume lots of system resources.

Upvotes: 3

Views: 2751

Answers (1)

Marcel Jackwerth
Marcel Jackwerth

Reputation: 54762

Just write the following code to remove the handler.

 document.onkeypress = null;

Since you are talking about attaching you maybe should check jquery which provides real bind (attach) and unbind (detach) for events like keypress.

Upvotes: 2

Related Questions