0

I am using this function:

function myFunction(){
var position = $(window).scrollTop();

$(window).scroll(function() {
    var scroll = $(window).scrollTop();
    if(scroll > position) {
         // scrolling downwards
         hypeDocument.showSceneNamed('Section 2', hypeDocument.kSceneTransitionCrossfade, 1.1);
    }
    position = scroll;
});

return false;
}

In my site, I want the user to get presented with a new page called a 'scene' (in the software I am using) every time they scroll down. This code works great once but when I set it up a second time for them to go to another 'scene' it just calls the first function again. Is there any way I can kill this function when scroll event is detected?

Thanks

dwinnbrown
  • 3,013
  • 7
  • 27
  • 53
  • 1
    possible duplicate of [Best way to remove an event handler in jQuery?](http://stackoverflow.com/questions/209029/best-way-to-remove-an-event-handler-in-jquery) – JJJ Jul 05 '15 at 12:08

2 Answers2

0

Just remove scroll event using either unbind or off method of jquery

$(window).off("scroll");

or

$(window).unbind("scroll");
Laxmikant Dange
  • 6,983
  • 4
  • 36
  • 60
  • ok. if I returned to this 'scene' would the function still run? – dwinnbrown Jul 05 '15 at 12:14
  • Event is already bind, and eventhandler function is already in memory, even if you remove that function, then also that code will be executable. you need to detach the event from dom. – Laxmikant Dange Jul 05 '15 at 12:22
  • Ok and do you know how I would go about doing that? If I applied the unbind to the first scroll, could I remove it when the scene was refreshed so that it would work on the same scene if they return to it? – dwinnbrown Jul 05 '15 at 12:26
  • You can use unbind method as per your condition. if you want to stop scroll on button click, then you can call it on button click. – Laxmikant Dange Jul 05 '15 at 12:29
  • @Laxmikant_Dange I am using variables now and have decided to use the `$(window).off("scroll");` method. Is there any way I could prevent downward scroll only? Thanks – dwinnbrown Jul 05 '15 at 17:30
0

You can use one() to execute the event only once. jQuery API. It has the same effect as Laxmikant's answer but just reducing the code to a single line.

function myFunction() {
  var position = $(window).scrollTop();

  $(window).one('scroll', function() { // Change
    var scroll = $(window).scrollTop();
    if (scroll > position) {
      // scrolling downwards
      hypeDocument.showSceneNamed('Section 2', hypeDocument.kSceneTransitionCrossfade, 1.1);
    }
    position = scroll;
  });

  return false;
}
m4n0
  • 25,434
  • 12
  • 57
  • 77