jQuery alert after 100 pixels scrolled

后端 未结 3 707
长发绾君心
长发绾君心 2020-12-15 06:35

Is it possible to fire an alert after a user scrolls 100 pixels.

Here\'s what I have so far but I know I\'m missing something;

$(window).scroll(func         


        
相关标签:
3条回答
  • 2020-12-15 07:12

    Try this:

    $(document).scrollTop() >= 100) {
        // ...
    }
    

    scrollTop() returns an integer. This version will evaluate to true once you have scrolled past 100px, which might be more appropriate.

    0 讨论(0)
  • 2020-12-15 07:16

    try

    document.documentElement.clientHeight + $(document).scrollTop() == 100
    
    0 讨论(0)
  • 2020-12-15 07:18

    Look at the window .scrollTop (returns an integer):

    $(window).scroll(function() {
        if ($(this).scrollTop() === 100) { // this refers to window
            alert("You've scrolled 100 pixels.");
        }
    });
    

    but if you have scrolled 102px it wont trigger the alert box.

    if you just want to trigger the alert once have a global variable that sets to true if it has been trigged:

    $(function(){
        var hasBeenTrigged = false;
        $(window).scroll(function() {
            if ($(this).scrollTop() >= 100 && !hasBeenTrigged) { // if scroll is greater/equal then 100 and hasBeenTrigged is set to false.
                alert("You've scrolled 100 pixels.");
                hasBeenTrigged = true;
            }
        });
    });
    

    or just unbind the scroll event once the alert box has been trigged:

    $(function(){
        $(window).bind("scroll.alert", function() {
            var $this = $(this);
            if ($this.scrollTop() >= 100) {
                alert("You've scrolled 100 pixels.");
                $this.unbind("scroll.alert");
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题