开发者

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

Imagine this is my page:

<p>hello</p>
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<p class="myPara">My Paragraph</p>

How can I alert a message when t开发者_运维问答he user has scrolled down to the paragraph with the class "myPara" and not before then?


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/


$(window).scroll(function(){
    console.log($('#myPara').offset().top < $(this).height() + $(this).scrollTop());
});


I had been thinking about the problem of attaching a scroll event (pointed out by @AndrewWhitaker), and my final thoughts are that there is no need to add a scoll event handler every x seconds, since you can just execute a setInterval and check in the callback whether the alert should be shown or not. e.g:

var showMessageInterval = window.setInterval(showMessageIfNeeded, 500);
// you could adjust the interval to the animation duration of the 
// message showing. In this way, the delay will be more "natural"

The showMessageIfNeeded callback would check the scrollTop value and show the message if needed. If the message is displayed, the setInterval have to be cleared to avoid the next executions:

function showMessageIfNeeded() {
    var scrollTop = $(window).scrollTop();
    var targetTop = $(".myPara").offset().top;
    if (scrollTop > targetTop) {
        alert('Show message');
        window.clearInterval(showMessageInterval);
    }
}


You can do this with the scrollspy jquery plugin. https://github.com/thesmart/jquery-scrollspy

$('.myPara').on('scrollSpy:enter', function() {
    console.log('enter:', $(this).attr('id'));
});

$('.myPara').on('scrollSpy:exit', function() {
    console.log('exit:', $(this).attr('id'));
});

$('.tile').scrollSpy();


Compare the page scroll position to your element top position, than call your function.

jQuery

$(document).on('scroll', function() {
  if ($(this).scrollTop() >= $('.myPara').position().top) {
    console.log('Reached');
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<p>hello</p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p class="myPara">My Paragraph</p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

ES6 (Pure JS, no jQuery)

var target = document.querySelector('.myPara');

document.addEventListener('scroll', () => {
  if (window.scrollY >= target.getBoundingClientRect().top) {
    console.log('Reached');
  }
})
<p>hello</p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<p class="myPara">My Paragraph</p>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜