0

I currently have a conditional running in jquery's scroll event, which doesn't seem to make a lot of sense since it will only execute once. I was wondering if there is any way to ensure that the conditional will only be evaluated once.

here's my code:

$window.scroll(function() {
  if (s1_doAnimate == true){
    s1_doAnimate = false;
  }
})
1
  • Is this a part of the code in scroll event or is this the only operation? Commented Aug 31, 2012 at 11:04

2 Answers 2

3

Use $.one

$(window).one('scroll', function(){
...
});
Sign up to request clarification or add additional context in comments.

Comments

2

You can unbind the handler once the condition has been met;

$window.scroll(function foo /* give the function a name */ () {
  if (s1_doAnimate == true){
    s1_doAnimate = false;

    // Unbind the handler referenced by the name...
    $window.off(foo);
  }
})

2 Comments

Wouldn’t this create a new function for each trigger? Maybe it’s better to store foo outside the handler? Just curious...
@David: No, the declaration is only processed once (before the function expression is passed to the scroll() function). IE < 9 will create 2 functions for it though (more);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.