0

I make a small jquery script. When you scroll on the page and your are over 350. Than a button is show. When you going back, the button is hide. This is the script:

var button = $('a[title*="terug naar boven"]');

$(document).bind('scroll', function(e) {
    if (window.scrollY > 350) {
        button.animate ({
            opacity: 1
        })
    }
    if (window.scrollY < 350) {
        button.animate ({
            opacity: 0
        })
    }
});

But the problem is. That the script succession is. When i scroll. The script is fire everytime. How can i fix this? That is script is fire one time.

Mike Vierwind
  • 1,482
  • 4
  • 23
  • 44

1 Answers1

0

To prevent the button from being animated if its already in the right state (either shown or hidden), you should maintain state of the button.

You can use a variable to do this

var buttonState = 0;
$(document).bind('scroll', function(e) {
    if (window.scrollY > 350 && buttonState == 0) {
        buttonState = 1;
        button.animate ({
            opacity: 1
        })
    }
    if (window.scrollY < 350 && buttonState == 1) {
        buttonState = 0;
        button.animate ({
            opacity: 0
        })
    }
});

Alternatively, you can also use the button's opacity level as state

If you want to run this only once, you can unbind handlers for the event

$(document).bind('scroll', function(e) {
    if (window.scrollY > 350) {
        button.animate ({
            opacity: 1
        })
    }
    if (window.scrollY < 350) {
        button.animate ({
            opacity: 0
        })
    }
    $(document).unbind('scroll');
});
Elvis D'Souza
  • 2,273
  • 1
  • 23
  • 31