How to detect page scroll to a certain point in jQuery?

How about:

var target = $(".myPara").offset().top;
var interval = setInterval(function() {
    if ($(window).scrollTop() >= target) {
        alert("made it!");
        clearInterval(interval);
    }
}, 250);

Here’s an example: http://jsfiddle.net/andrewwhitaker/24M3n/1/

You might be tempted to attach an event handler to the window scroll event, but John Resig advises against it (Scroll down to “Best Practices”).

Update: As @AbdulJabbarWebBestow points out, it might be a bad idea to unnecessarily run a function every 250ms. Here’s an updated example that only runs once, 250ms after the first time a user scrolls:

var target = $(".mypara").offset().top,
    timeout = null;

$(window).scroll(function () {
    if (!timeout) {
        timeout = setTimeout(function () {
            console.log('scroll');            
            clearTimeout(timeout);
            timeout = null;
            if ($(window).scrollTop() >= target) {
                alert('made it');
            }
        }, 250);
    }
});

Example: http://jsfiddle.net/24M3n/858/

Leave a Comment