Unbind special keypress event
Asked Answered
F

2

13

I've got a question regarding jQuery keypress events. I've got the following (working) code:

$(document).bind('keypress', function(event) {

    if ($('#myDiv').is(':visible')) {

        if (event.which == 102) {
            // ...do something...
        }

    }
    else {
        if (event.which == 102) {
            return;
        }
    }

});

I always "unbind" the event with binding another "over" it. I know that I can unbind it with .unbind('keypress') but I got more keypress events and when i unbind this with $(document).unbind('keypress') all my events get lost.

Can I do something like "keypress.102" to only unbind this particular "key" or how can this be done?!

Fennell answered 21/9, 2011 at 13:56 Comment(0)
T
30

You were on the right track. That's called namespaced events, i.e. labelling specific bindings using <event_name>.<namespace> (in your case, "keypress.102").

For example:

$(document).bind("keypress.key102", function(event) {
    if ($('#myDiv').is(':visible')) {

        if (event.which == 102) {
            // ...do something...
        }

    }
    else {
        if (event.which == 102) {
            return;
        }
    }
});

you can later unbind that without affecting other bound keypress events:

$(document).unbind("keypress.key102");
Tranche answered 21/9, 2011 at 14:0 Comment(0)
G
1

Use a namespaced event.

http://docs.jquery.com/Namespaced_Events

Glottochronology answered 21/9, 2011 at 13:58 Comment(1)
Can you give an example of how the OP should use namespaced events to solve this problem?Neoteric

© 2022 - 2024 — McMap. All rights reserved.