Reputation: 1071
I have created a small jQuery plugin that creates sticky sidebars and I've tried to create a "destroy" method which removes the stickyness. It works fine however I'm using it on multiple elements on the page (sticky sidebar within accordions) and when I destroy one, it removes the scroll events for all the others.
$parent.find('.js-opps-aside').stickAside();
var thisScroll = $(window).on('scroll', enqStick);
...
$(window).off('scroll', thisScroll);
I thought that was how to unbind specific scroll events, however, as I said it removed all the event handlers. I just want it to remove the scroll event for this specific element it was called upon, and leave the other elements with their scroll events intact.
Upvotes: 1
Views: 1141
Reputation: 111
According to jQuery stacking logic thisScroll is $(window). What you would like to do is:
// Binding a handler
$(window).on('scroll', enqStick);
// removing handler by bound function handler
$(window).off('scroll', enqStick);
Upvotes: 1
Reputation: 2062
When you use $().off(), the second parameter is a reference to the event handler, and you try to off with thisScroll
but it is a jQuery collection.
You should use this :
$(window).off('scroll', enqStick);
You can use another solution that is think is better, just suffit the event name
$parent.find('.js-opps-aside').stickAside();
$(window).on('scroll.myCustomScroll', enqStick);
...
$(window).off('scroll.myCustomScroll');
$().off
with only one parameter will off all event callbacks associated with the event, in our case it will of all scroll.myCustomScroll
Upvotes: 2