Reputation: 2077
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.
.scrollTop() == 3
which isnt always the case with the scroll wheel..scrollTop() == 3
could be true multiple times.Upvotes: 2
Views: 5710
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