How to remove the document.onkeydown event handler?

I have this code, I will need to programmatically overridde or remove onkeydown from the document (for example, using a simple condition)

document.onkeydown = function (f) { myMethod(); }; 

Any idea how to do this?

+6
source share
4 answers
 document.onkeydown = null 

You can use jquery to handle your events for you, the method you use is less commonly used and does not allow multiple subscribers.

Check out the documentation here:

http://api.jquery.com/on/

Example:

 $(document).on("keydown", function(){ doStuff(); }) // unsubscribe all handlers $(document).off("keydown"); 
+11
source

You can remove it with:

 document.onkeydown = null; 

If you want to restore it, you can first save it in a variable:

 var saved_keydown = document.onkeydown; document.onkeydown = null; //... later document.onkeydown = saved_keydown; 
+5
source

You cannot delete it, you can only attach a new one that does nothing, for example:

 document.onkeydown = function () {}; 

using jQuery you can do:

 $(document).on('keydown', myMethod); 

and delete

 $(document).off('keydown', myMethod); 
+1
source

The easiest way is to set to null

 document.onkeydown = null; 
+1
source

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


All Articles