开发者

How to detect when the user has scrolled to a certain area on the page using jQuery? [duplicate]

This question already has answers here: Closed 11 years ago.

Possible Duplicate:

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

Chec开发者_Python百科k if element is visible after scrolling

How can I detect when the user has reached this div:

<br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />

<div id="theTarget">I have been reached</div>

EDIT

Got the answer from this question:

Check if element is visible after scrolling

So I just did this:

function isScrolledIntoView(elem)
{
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();
    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();
    return ((elemBottom >= docViewTop) && (elemTop <= docViewBottom) && (elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

$(window).scroll(function() {    
    if(isScrolledIntoView($('#theTarget')))
    {
        alert('visible');
    }    
});


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

jQuery

$(document).on('scroll', function() {
  if ($(this).scrollTop() >= $('#theTarget').position().top) {
    console.log('I have been reached');
  }
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div id="theTarget">I have been reached</div>
<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('#theTarget');

document.addEventListener('scroll', () => {
  if (window.scrollY >= target.getBoundingClientRect().top) {
    console.log('I have been reached');
  }
})
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<div id="theTarget">I have been reached</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>


I think you can accomplish your goal by comparing values from your div position

var divPosition = $("#theTarget").offset().top;

and the window scroll position

var scrollPosition = window.scrollY;


There is a jquery appear plugin that I believe does exactly what you are asking.

http://plugins.jquery.com/project/appear

$('#theTarget').appear(function() {
  $(this).text('Hello world');
});

It also ties into resize, and initial window size ... etc, etc, etc.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜