Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

javascript - jQuery alert after 100 pixels scrolled

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(function() {
    if (document.documentElement.clientHeight + 
        $(document).scrollTop() == "100px")
    { 
        alert("You've scrolled 100 pixels.");
    }
});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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");
        }
    });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...