Using off() on elements registered inside each()
in Using jQuery
•
7 years ago
So the issue I'm having here seems like it shouldn't be an issue in the first place, but after doing some research it seems jquery's off() method will not off events that are registered dynamically inside an each() statement. Since the selector of the this statement for some reason doesn't match the original selector when the on() method is used.
Here is my scenario:
$elements.each(function(index, el) {
var $this = $(this);
$this.off("." + name);
if(...) {
$this.on("scroll." + name, function(e, scroll) {
// do stuff on scrolling
});
}
});
I should point out that this piece of code is intended to be executed multiple times hence why the off() call is made first. Anyway, in this situation the off() call has no effect at all on the elements events. So I changed it to call on the jquery object itself using a filter method rather than an each statement, and it still didn't work. Like so:
$elements.off("." + name);
$elements.filter(...).on("scroll." + name, function(e) {
// do stuff on scrolling
});
Anyone have any ideas how I should resolve this. From a logical point of view this should work perfectly fine and the element should be what is referenced in when calling off() (at least logically that would make more sense).
Can also see the stackoverflow question
Thanks!
1