0

So I have a scroll event that fires when the user scrolls to a certain point on the site. It works until you hit that point and want to keep scrolling, then it will fire continuously with every single scroll. I want to fire ONE time and then just not fire anymore.

 $(window).on('scroll', function() { var y_scroll_pos = window.pageYOffset; var scroll_pos_test = 450; // set to whatever you want it to be if(y_scroll_pos > scroll_pos_test) { alert("hey you hit it"); } }); 

I set up a demo below:

JSFiddle

1
  • @nnnnnn yes I tried to add a var that set it to false inside but it didn't fix it. Maybe offer a solution instead of pointing that out. Commented Mar 5, 2017 at 1:14

2 Answers 2

3

Of course it keeps firing with every scroll - you haven't removed the scroll event handler, and if the user keeps scrolling down the if condition will continue to be true for subsequent scroll events. Note that the handler is also firing for every scroll before the user reaches that point of the page, it just doesn't do anything noticeable because of the if.

"I want to fire ONE time and then just not fire anymore."

The obvious solution would be to just call the .off() method to remove the scroll handler once it's no longer required:

$(window).on('scroll', function() { var y_scroll_pos = window.pageYOffset; var scroll_pos_test = 450; // set to whatever you want it to be if(y_scroll_pos > scroll_pos_test) { $(window).off('scroll'); // <--- add this alert("hey you hit it"); } }); 
Sign up to request clarification or add additional context in comments.

2 Comments

This works great too, I honestly did not know there was an off method. Thanks for teaching me something!
You're welcome. I'd recommend taking half an hour to browse through the list of all jQuery methods and selectors - don't try to memorise it all or anything, but just make a mental note of whichever methods seem useful to you.
2

You can set a variable once the scroll point has been met, and only alert if that variable isn't set.

 var scrolled = false; $(window).on('scroll', function() { var y_scroll_pos = window.pageYOffset; var scroll_pos_test = 450; // set to whatever you want it to be if(y_scroll_pos > scroll_pos_test && !scrolled) { alert("hey you hit it"); scrolled = true; } });
.scroll-text{ Height:1000px; width:100px; background-color:Yellow; } .scroll-target{ Height:600px; width:100px; background-color:green; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="scroll-text"> <p> Scroll Down </p> </div> <div class="scroll-target"> <p> You found me! </p> </div>

2 Comments

This is exactly what I was trying to do, I was putting the "var scrolled" in the wrong spot this whole time. Thanks!
@Jiroscopes np!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.