Jonathan Eckman
Jonathan Eckman

Reputation: 2077

Run function on first scroll, then never again

I need to run a function the first time .scrollTop() changes and then never again. I tried a couple things including the following, but no luck:

var view = $('#workspace');

view.bind("scroll resize", function() {
  doThisEveryScroll();
  if(view.scrollTop() == 3) {
    doThisOnFirstScroll();
  }
});

This is wrong for a number of reasons but I am not sure how to approach this any other way.

  1. This will only run if the user happens to hit .scrollTop() == 3 which isnt always the case with the scroll wheel.
  2. .scrollTop() == 3 could be true multiple times.

Upvotes: 2

Views: 5710

Answers (1)

Blender
Blender

Reputation: 298532

Use .one() to setup an event handler that detaches itself once it has been called:

$('#workspace').on('scroll resize', function() {
  doThisEveryScroll();
}).one('scroll resize', function() {
  if (Math.abs(100 - $(this).scrollTop()) < 20) {
    doThisOnFirstScroll();
  }
});

You can also provide a margin of error for your target scroll position by calculating the distance from your target:

Math.abs(100 - $(this).scrollTop()) < 20

This will return true if the user is within 20px of 100px.

Upvotes: 7

Related Questions