How do I make a shortcut key WITHOUT getting input from text fields

I am quiet new to Javascript and so I decided to make a shortcut key userscript for m.youtube.
It does work but when I am using that shortcut(Ctrl+Z to undo text) in a text field for writing a comment this happens

I could not find any help with a google search or trying find it on forums, I could be using the wrong terms for searching it.


Current Code

$(function(){
    document.onkeydown = function(evt) {
        evt = evt || window.event;
        if (evt.ctrlKey && evt.keyCode == 90) {
            alert("Ctrl-Z");
        }
    };
});

Goal: I don’t want the shortcut to run in a textfield when I press the shortcut key.

My first thought is to use a different shortcut combination. Ctrl-Z is pretty standard for undo and you should probably not hijack a common shortcut for your own use or you run into issues like this. Perhaps add another key, such as Ctrl+Alt+Z.

I suppose you could look at the event target and if it is an input that receives text then you could just ignore it.

1 Like

I agree, but that was just an example for me to try. I was trying to make a shortcut for just “s” key to make a quick search.


Yes, thank you. I was able to find this solution

$(function() {
    document.onkeydown = function(evt) {
        evt = evt || window.event;

        if (evt.ctrlKey && evt.keyCode == 90) {
            if (!(evt.target instanceof HTMLTextAreaElement) && !(evt.target instanceof HTMLInputElement)) { // This will ignore textarea and input elements
                alert("Ctrl-Z");
            }
        }
    };
});
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.