How to correctly detach event handler in jQuery

jquery, jquery-events

Solution

use jquery off

// assume you have a method for reuse purpose
function YourFunction(){
    // do something
};

$(document).on("scroll", YourFunction);
$(document).off("scroll", YourFunction);

Note that anonymous function won't work in this case unless you want to detach all event handlers:

$(document).off("scroll");

You can also specify a "namespace" when "on" and "off" events:

// delegate events under the ".validator" namespace
$(document).on("click.validator", function(){
    // do something
});

// remove only event handlers in the ".validator" namespace
$("form").off(".validator");

Problem

I have this jQuery function that centers element vertically with scroll support: ``` $.fn.center = function () { var self = this; this.css("position", "absolute"); this.css("top", ($(window).height() - this.height()) / 2 + $(window).scrollTop() + "px"); $(document).on("scroll", function () { self.center(); }); return this; }; ``` and it's used along with jQuery Block UI plugin: ``` $('#cph') .block(finalOptions) .find('.blockUI.blockMsg') .center(); ``` Every time a UI needs to be blocked, I execute second code snippet. But when I unblock UI, I just simply remove it with Block UI API, but I do nothing with scroll event handler. If I block/unblock UI many times, I'll have many event handlers registered to scroll event - which I guess is bad. But I don't know how to properly address that issue. Could you advise?

Original source