Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unbind special keypress event

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?!

like image 919
Mikaelik Avatar asked Sep 21 '11 13:09

Mikaelik


People also ask

How to remove keydown event in JavaScript?

Using the removeEventListener() method The JavaScript built-in function removeEventListener() removes an event handler from an element for a connected event. For instance, you can use removeEventListener() to get rid of a click event listener if a button is disabled after one click.

How to unbind an event in jQuery?

jQuery unbind() MethodUse the off() method instead. The unbind() method removes event handlers from selected elements. This method can remove all or selected event handlers, or stop specified functions from running when the event occurs. This method can also unbind event handlers using an event object.

What is the difference between jQuery's change () and keypress () events?

The change event occurs if the value has been changed when the element loses focus. The keypress event occurs every time you press down and release a (non control) key.


2 Answers

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");
like image 177
Shawn Chin Avatar answered Nov 15 '22 18:11

Shawn Chin


Use a namespaced event.

http://docs.jquery.com/Namespaced_Events

like image 27
BNL Avatar answered Nov 15 '22 20:11

BNL