joe
joe

Reputation: 69

Detect window scrolling only once Jquery

I want to show an alert after the user has scrolled 200px downwards. Single time, no more.

$(window).scroll(function(){if($(this).scrollTop()>200){
                                alert("SQL code executed"); 

                                }

Using this code, the alert appears anytime, How can I make it to appear only once? I need to execute an sql query, but with this current code the sql can be executed so many times as long as the user moves the scroll in the page.

Upvotes: 0

Views: 47

Answers (2)

Abraão Morais
Abraão Morais

Reputation: 36

You can unbind the event before or after (I did it after) the execution of the SQL code.

See the below snippet.

$(window).scroll( function(){		
  	if($(this).scrollTop()>200){
    	  alert("SQL code executed"); 
          $(this).unbind("scroll");
  	}
  }
);
body {
  height:1800px;      
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Ctznkane525
Ctznkane525

Reputation: 7465

Have a boolean variable that you reference. Once it's true, don't call again.

var previousCalled = false;

$(window).scroll(function(){if($(this).scrollTop()>200 && !previousCalled){
                                alert("SQL code executed"); 
                                previousCalled = true;
                                }

Upvotes: 0

Related Questions