Reputation: 11140
In a web page I have a button when clicked it calls a JavaScript function.
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.
When I close the modal dialog I want to stop the keystroke processing.
consider that I click a button and function sam()
is called.
function sam()
{
document.onkeypress = function(e) { processKeystroke(e); }
}
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.
Now I am closing the modal dialog and with that I don't want function(e) { processKes...}
to be called.
What should I do to remove the attached event listener from document.onkeypress
.
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.
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
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