0

How to prevent this double triggering at the bottom of the webpage.

Here is the option when you reach 100px from the bottom you see alert message but when you hit bottom you see it too and I only want to see it once even if you hit the bottom of the webpage.

Here is the link:

double triggering

And the code:

 $(window).scroll(function() {   
   if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
       alert("bottom!");
   }
});

EDIT:

Problem is that I am appending multiple divs to the website and I do not have fixed number of them, so that is why I need to check if I have hit the bottom of the page.

user123_456
  • 5,635
  • 26
  • 84
  • 140
  • search before you ask , same question here http://stackoverflow.com/questions/3898130/how-to-check-if-a-user-has-scrolled-to-the-bottom – Hussein Nazzal Mar 02 '13 at 20:40

3 Answers3

1

You can set a flag to control this behaviour:

var alerted = false;
$(window).scroll(function () {
    if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
        if (!alerted) {
            alert("bottom!");
            alerted = true;
        }
    }
    else alerted = false;
});

http://jsfiddle.net/gWD66/1117/

dfsq
  • 191,768
  • 25
  • 236
  • 258
0

The general answer is to simply remove the event handler once it has triggered.

jQuery can do this for you, however, with its .one() event handler function.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • Using `.one` doesn't work in this use case because the scroll handler will usually need to be called more than once. – pdoherty926 Mar 02 '13 at 20:42
0

try this:

 var beenOnBottom = false;
 $(window).scroll(function() {  

   if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
       if(!beenOnBottom)
       {
           alert("bottom!");
           beenOnBottom = true;
       }
   }
});

If you want to show the message when you go up again, you can reset the beenOnBottom variable as soon as go above the 100px value

Pbirkoff
  • 4,642
  • 2
  • 20
  • 18