I ask a specific question about jquery scroll events, but it seems like the answer could have implications to jquery events in general (which I am also interested in knowing).
Suppose that jquery plugin A
(e.g., jquery.scrollspy.js) binds a scroll event to $(window)
Now say that some site imports plugin A
, but it also has its own custom javascript file B
, which binds another .scroll()
event to $(window)
.
Later on, javascript file B
wants to unbind its own scroll event, and leave jquery plugin A
intact. How is this done?
and...
Is this method universal to all jquery events?
I ask a specific question about jquery scroll events, but it seems like the answer could have implications to jquery events in general (which I am also interested in knowing).
Suppose that jquery plugin A
(e.g., jquery.scrollspy.js) binds a scroll event to $(window)
Now say that some site imports plugin A
, but it also has its own custom javascript file B
, which binds another .scroll()
event to $(window)
.
Later on, javascript file B
wants to unbind its own scroll event, and leave jquery plugin A
intact. How is this done?
and...
Is this method universal to all jquery events?
Share Improve this question edited Apr 21, 2013 at 20:22 Alex W 38.2k13 gold badges111 silver badges114 bronze badges asked Apr 21, 2013 at 20:12 Colin BroganColin Brogan 7481 gold badge10 silver badges27 bronze badges 1- For those interested in doing this without jQuery: stackoverflow./questions/4402287/… – Alex W Commented Apr 21, 2013 at 20:22
3 Answers
Reset to default 8jQuery remends to use on and off instead of bind and unbind.
function scrollEvent()
{
}
$(window).on('scroll',scrollEvent);
$(window).off('scroll',scrollEvent);
http://api.jquery./on/
Best to use jQuery's .on() and .off() methods rather than .bind() and .unbind().
As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document.
You can also namespace the event by adding a custom suffix to the event name. You can then access that particular event later (to unbind for example)...
$(window).on('scroll.myscroll', function () {
// do something on scroll event
});
an den...
$(window).off('scroll.myscroll'); // unbind my namespaced scroll event
See https://css-tricks./namespaced-events-jquery/
This is easy. Didn't do enough research before asking question:
var fileBScrollEvent = function() {
// do something on scroll event
}
$(window).bind('scroll',fileBScrollEvent);
...later on in the code...
$(window).unbind('scroll',fileBScrollEvent);