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?
use jquery off
Note that anonymous function won’t work in this case unless you want to detach all event handlers:
You can also specify a “namespace” when “on” and “off” events: