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

Time:10-03

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

Alert popups when using the shortcut in a textfield

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.

CodePudding user response:

You can check if event target is type of input. Try this:

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

        if (evt.ctrlKey && evt.keyCode == 90) {
            if (!(evt.target instanceof HTMLTextAreaElement) && !(evt.target instanceof HTMLInputElement)) {
                alert("Ctrl-Z");
            }
        }
    };
});

function check () {
        document.onkeydown = function(evt) {
            evt = evt || window.event;
            console.log(evt.target)
            if (evt.ctrlKey && evt.keyCode == 90) {
                if (!(evt.target instanceof HTMLTextAreaElement) && !(evt.target instanceof HTMLInputElement)) {
                    alert("Ctrl-Z");
                }
            }
        };
    }
    
    check()
<textarea id="w3review" name="w3review" rows="4" cols="50">
  hello
  </textarea>
  <input type="text" >

If the event target is not of type input you do alert("Ctrl-Z");

  • Related