frank
frank

Reputation: 31

Cannot get onScroll function to fire only once

I'm pretty new to JavaScript and found myself a little stuck on one seemingly super simple task with an onScroll function.

I have the following code (see below) which is working great. However, it currently fires every time the user scrolls up or down, returning to that particular vertical location on the page. I only want it to fire the first time it is scrolled to after a page load.

Please help!

Big respect and many thanks in advance!

$(window).scroll(function () {
  $('#pro1').each(function () {
     var topOfWindow = $(window).scrollTop(),
     bottomOfWindow = topOfWindow + $(window).height();

     var imagePos = $(this).offset().top;

     if(imagePos < bottomOfWindow-200 && imagePos >= topOfWindow-500){
       $(this).addClass('bigEntrance2'); 
     }else{
       $(this).removeClass('bigEntrance2');
     }
  });
});

Upvotes: 0

Views: 1051

Answers (2)

Ryan K
Ryan K

Reputation: 4053

You can use the one method. It is the same as the on method, but only fires once per page load. So for your example, it would look like this:

$(window).one("scroll", function()
{
  # Scroll code here
});

Edit: I think I understand your question better. You want the code to check when you're in that scroll region, but only execute once. So to do that, you first should designate a custom event:

$(window).one("customEvent", function()
{
  $(this).addClass('bigEntrance2');
});

And then trigger that event when you want:

if(imagePos < bottomOfWindow-200 && imagePos >= topOfWindow-500)
{
  $(this).trigger("customEvent");
}

That way, the class 'bigEntrance2' is only applied once, which is what I think you want.

Upvotes: 1

Andr&#233; Silva
Andr&#233; Silva

Reputation: 1108

Well you can use a variable and use it as a flag. The first time the user scrolls once the page loads, you set it to true. After that, you check that variable to avoid doing always the same code.

var alreadyScrolled = false;
$(window).scroll(function () {
     if(!alreadyScrolled) {
          $('#pro1').each(function () {
               var topOfWindow = $(window).scrollTop(),
               bottomOfWindow = topOfWindow + $(window).height();

               var imagePos = $(this).offset().top;

               if(imagePos < bottomOfWindow-200 && imagePos >= topOfWindow-500){
                    $(this).addClass('bigEntrance2'); 
               }else{
                    $(this).removeClass('bigEntrance2');
               }
          });
          alreadyScrolled = true;
     }
});

Upvotes: 0

Related Questions