Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing a jQuery event handler while inside the event handler

I have a keydown event handler that I attach to my document so I can watch the keydown event everywhere. However, after a condition is met, I want to be able to remove that and only that handler. How can I do this?

This is my current handler:

    $(document).keydown(function(event){
        console.log(event);

        var tag = event.target.tagName.toLowerCase();
        if(event.which = 27 && tag != 'input' && tag != 'textarea'){    //escape has been pressed
            _dismissModal(modal_id);
        }
    });

I want to remove this keydown event handler after _dismissModal is called. How can I do this without removing all keydown event handlers?

like image 719
Malfist Avatar asked Jan 28 '14 20:01

Malfist


Video Answer


4 Answers

you can use jquery off() method. You also could put your keydown logic in to a separate function so you only can target that keydown action in your off method.

var mykeydownfunction= function(){
    console.log(event);

    var tag = event.target.tagName.toLowerCase();
    if(event.which = 27 && tag != 'input' && tag != 'textarea'){    //escape has been pressed
        _dismissModal(modal_id);
        $(this).off('keydown', mykeydownfunction);// $(this) is the document
    }
}  

 $(document).on('keydown', mykeydownfunction);
like image 50
kasper Taeymans Avatar answered Oct 10 '22 03:10

kasper Taeymans


Use .off() to remove the event handler.

$(document).on("keydown", function(event){
    console.log(event);

    var tag = event.target.tagName.toLowerCase();
    if(event.which = 27 && tag != 'input' && tag != 'textarea'){    //escape has been pressed
        _dismissModal(modal_id);
        $(this).off("keydown");
    }
});
like image 42
James Hibbard Avatar answered Oct 10 '22 03:10

James Hibbard


This has been answered already but using namespaces with removing events is really helpful and makes sure you don't cause any side effects.

// add click event with my.namespace as the namespace
$('element').on('click.my.namespace', function (e) {
    // do something
});

// remove my.namespace click event from element
$('element').off('click.my.namespace');

You can open up the dev console and look at the events of an element with

$._data($('element')[0], 'events');

Open up the Object and you will see a click array. Expand your event and you will see the namespace actually shows up as

namespace.my

and not

my.namespace

http://api.jquery.com/on/

Search for Event names and namespaces for more info.

like image 23
VtoCorleone Avatar answered Oct 10 '22 04:10

VtoCorleone


When the condition is met, use .off()

$(document).off('keydown');
like image 2
Venkata Krishna Avatar answered Oct 10 '22 04:10

Venkata Krishna