Harts
Harts

Reputation: 4093

jquery off is not triggered

Is there anything wrong with this code?

$(document).ready(function() {

    if($("#textbox-id-recipient").val()) {
        console.log("In");


        $(document).on("click", "#textbox-id-recipient", function(event) {
            addEmail($(this));
        });

        $('#textbox-id-recipient').trigger('click');

        $("#textbox-id-recipient").off("click");
    }

...
});

So, after page refresh, if textbox has something, it will trigger the click event, which trigger the one "on" event, but after that it supposed to take off the event, but somehow, when I manually click the textbox, the on event still triggered

Upvotes: 1

Views: 99

Answers (4)

Ja͢ck
Ja͢ck

Reputation: 173572

Review

Considering this statement:

$(document).on("click", "#textbox-id-recipient", function(event) {
    addEmail($(this));
});

You're binding a click handler to document, which is called when a click event bubbles all the way up from where the click starts.

    $('#textbox-id-recipient').trigger('click');

This will simulate a click event on your element; if the event is not handled, jQuery makes the event bubble up the element tree via the parents until it reaches document.

    $("#textbox-id-recipient").off("click");

Even though the above click trigger works as expected, .off() will only look at the current element, i.e. it doesn't automatically "bubble it up".

Alternative 1

Therefore, you should disable the click handler on the same element as where you attached it, i.e.:

$(document).off("click", "#textbox-id-recipient");

Btw, knowing that identifiers must be unique, you might as well attach the event handler on #textbox-id-recipient directly unless the element is only added later.

$('#textbox-id-recipient').on('click', function(event) {
});

Alternative 2

Also, if the click should only be handled once, use .one():

$('#textbox-id-recipient').one('click', function(event) {
});

Or, if you want to use event delegation:

$(document).one('click', '#textbox-id-recipient', function(event) {
});

Upvotes: 2

jmartsch
jmartsch

Reputation: 352

Try removing the handler by using this code. It should work:

$(document).off("click", "#textbox-id-recipient");

Fiddle here : http://jsfiddle.net/yntyF/1/

Upvotes: 1

Arun P Johny
Arun P Johny

Reputation: 388316

Use .one()

if($("#textbox-id-recipient").val()) {
    console.log("In");

    $("#textbox-id-recipient").one("click", function(event) {
        addEmail($(this));
    });

    $('#textbox-id-recipient').triggerHandler('click');
}

Demo: Fiddle

Upvotes: 3

Kyle Trauberman
Kyle Trauberman

Reputation: 25684

Bind your event to the element, not the document.

$('#textbox-id-recipient').on("click", function(event) {
    addEmail($(this));
});

$('#textbox-id-recipient').trigger('click');

$("#textbox-id-recipient").off("click");

Upvotes: 2

Related Questions