How to execute a JS function when the user reaches a specific element in the page?

孤街醉人 提交于 2019-12-25 07:07:36

问题


How can I automatically execute a JavaScript function when the user reaches a specific position on the page?

When I scroll down to the bottom of the page, an AJAX-call shall be executed that loads more content so that you can scroll down further.

Nothing should happen if the user scrolls down and then scrolls up again by the same distance.

This is the call of the ajax function that I have and want to execute:

refresh('refresh_status', 'refresh_status.php', '', '', '', 'refresh');

回答1:


Fixed for default JavaScript: http://cdpn.io/xdjmG

HTML:

<div id="page" style="min-height: 10000px;">
    <div id="anotherElement" style="margin-top: 500px; min-height: 500px; background-color:red"></div>
</div>

JavaScript, will alert when page reaches "anotherElement":

window.addEventListener('scroll', function(){
  var place = document.body.scrollTop;
  var alertOn = document.getElementById('anotherElement').offsetTop;
  if(place > alertOn){
    alert('Function execute here');
    this.removeEventListener('scroll', arguments.callee, false);
  }
});


来源:https://stackoverflow.com/questions/18250830/how-to-execute-a-js-function-when-the-user-reaches-a-specific-element-in-the-pag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!