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?
The . off() method removes event handlers that were attached with .
Go to the objects tab, view the Document object (don't click on edit) and scroll down to Event Handlers. Select the one to delete and press delete.
The event listeners need to be removed due to following reason. Avoid memory leaks, if the browser is not handled it properly. Modern browsers will garbage collect event handlers of removed DOM elements but it is not true in cases of legacy browses like IE which will create memory leaks.
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");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With