Shout It Web Solutions
Shout It Web Solutions

Reputation: 159

Prevent jQuery action from happening a second time on scroll

I have some code that detects if an element is in the viewport and then fires some code, it does this by calculating the distance from the top on scroll, the issue I'm having is it re-runs the code every time a scroll event happens and the element is above the fold, is there a way to make it so it only fires once?

$(document).ready(function(){
    $(document).scroll(function(){
    var scrollTop     = $(window).scrollTop(),
    elementOffset = $('.numbers').offset().top,
    distance      = (elementOffset - scrollTop);

    if(distance < $(window).height()){
      $('.ones').delay(1000).hide(1000, function(){
       $(this).html('6').show(1000, function(){
         $(this).delay(15000).hide(1000, function(){
            $(this).html('5').show(1000);
          });
        }); 
      });
      }else{
        return false;
      }    
    });
});

Upvotes: 0

Views: 117

Answers (1)

baao
baao

Reputation: 73231

add

flag=true

directly after document ready, check for it in your if

if (distance<... && flag===true)

and set it to false in the if clause

flag = false

Upvotes: 1

Related Questions