Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disable keydown shortcuts if input(s) is focused

I have few inputs which you focus them using keycodes.

I am trying to: when focus on inputs, disable the keycodes function and when not focused, enable.

I tried this:

var hotkeys_function = false;
if (!hotkeys_function ){
    $(document).keydown(function(e) { 
        if (e.keyCode == 71) { 
        $("#input1").fadeIn();
        $("#input1").focus().select();
            var hotkeys_function = true;
        }
    });

}

And this:

if ($("#input1").select()) {
    var hotkeys_function = true;
}

but none seem to be working.

like image 378
jQuerybeast Avatar asked Nov 23 '25 14:11

jQuerybeast


1 Answers

Not $("#input1").select() but $("#input1").focus().

In fact, no variables are needed, you can just check and return dynamically whether an input is focused or not.

$(document).keydown(function(event) {
    if($("#input1").is(":focus")) return; //Will fail if already focused. 

    if (event.keyCode == 71) { //g 
        $("#input1").fadeIn();
        $("#input1").focus().select();
    }
});

Working example.

like image 123
Madara's Ghost Avatar answered Nov 25 '25 02:11

Madara's Ghost



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!