8

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?

Alex W
  • 37,233
  • 13
  • 109
  • 109
Colin Brogan
  • 728
  • 10
  • 26
  • For those interested in doing this without jQuery: http://stackoverflow.com/questions/4402287/javascript-remove-event-listener – Alex W Apr 21 '13 at 20:22

3 Answers3

8

jQuery recommends to use on and off instead of bind and unbind.

function scrollEvent()
{
}
$(window).on('scroll',scrollEvent);
$(window).off('scroll',scrollEvent);

http://api.jquery.com/on/

Ruben-J
  • 2,663
  • 15
  • 33
6

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.com/namespaced-events-jquery/

JPPP
  • 61
  • 1
  • 2
0

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);
Colin Brogan
  • 728
  • 10
  • 26