jQuerybeast
jQuerybeast

Reputation: 14490

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.

Upvotes: 3

Views: 2868

Answers (2)

pimvdb
pimvdb

Reputation: 154838

What you could do is this, without any other variables: http://jsfiddle.net/pimvdb/YnVPQ/.

$(document).keydown(function(e) {
    if (e.keyCode == 71) {
        if($("input").is(":focus")) return; // abort if any focused textboxes

        $("#input1").fadeIn();
        $("#input1").focus().select();
    }
});

Upvotes: 0

Madara's Ghost
Madara's Ghost

Reputation: 174957

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.

Upvotes: 4

Related Questions