Search code examples
jqueryfunctionscrollalertscrolltop

run jQuery function only ONCE (instead of endless loop when event occur)


I have this jQuery code that fires when user scroll down to the point of ad class height (and after). The problem is that I want it to run only ONCE and stop alert. Very simple tweak (and without settimeout nor setting a variable ;)

css:

header{width:100%;height:200px;background:teal;}
.ad{width:500px;height:120px;margin:0 auto;background:red;}
article{width:100%;height:1500px;background:yellow;}

html:

<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
</head>
<body>
  <header>
    <div class='ad'></div>
  </header>
  <article></article>
</body>
</html>

jquery :

$(function(){
  $(window).scroll(function(){
    var aTop = $('.ad').height();
    if($(this).scrollTop()>=aTop){
        alert('header just passed.');
    }
  });
});

Thanks !


Solution

  • here you go:

    http://jsfiddle.net/hamoom/qX6bn/

    $(function(){
    
    var alerted = false; 
    
    $(window).scroll(function(){
    var aTop = $('.ad').height();
    
    if($(this).scrollTop()>=aTop && !alerted){
        alerted = true;
        alert('header just passed.');
    } 
    else if($(this).scrollTop()<=aTop && alerted){
        alerted = false;
    }
    });
    });
    

    i just use a flag to prevent it firing that alert over and over. i reset it in the "else" block so that when you scroll back up you can get the same alert again