scrollTop() is a jQuery function that will wait until the browser scrolls a certain distance, then fire the code.  A use case example for this would be an alert that only shows up after the user has scrolled to a certain anchor or “x” pixels.

This example will trigger the alert if you scroll to 100px exactly.  If you scroll to 125px it would not trigger.

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

This example will trigger the alert once you scroll to 100px or greater and set a flag so it will not trigger again.

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

This example is similar to the above, but instead of setting a flag, it unbinds the trigger altogether.

$(function(){
    $(window).bind("scroll.alert", function() {
        var $this = $(this);
        if ($this.scrollTop() >= 100) {
            alert("You've scrolled 100 pixels.");
            $this.unbind("scroll.alert");
        }
    });
});

Leave a Reply