简体   繁体   中英

Trigger action when reaching a target div in Javascript

I am outputting a result set with PHP and MySQL, each result wrapped in a DIV. A JavaScript function triggers an action as soon as the user scrolls to the bottom of the browser window.

$(window).scroll(function(){
  if ($(window).scrollTop() == $(document).height() - $(window).height()){
    trigger_funtion();
  }
}); 

Each item (class ".item") of the PHP result is placed into a general wrapper DIV (class ".results") containing all items.

How can I change this function above so that the action is triggered as soon as the user "scrolls" or "arrives" at the last DIV which was created from the result set, rather than when he hits the bottom of the browser window?

I have tried the following, but it does not work

$(window).scroll(function(){
  if  ($(window).scrollTop() == $(".results .item:last")){
    trigger_funtion();
  }
}); 

You need to use .position().top and I suggest to use >= rather than == since you cannot rely on the numbers being equal

if  ($(window).scrollTop() >= $(".results .item:last").position().top)

or

var winHeight = $(window).height(); // viewport 
if  ($(window).scrollTop()+winHeight >= $(".results .item:last").position().top)

Here is the code for when the last item hits the top

Live Demo

$(function() {
  var $item = $(".results .item:last"); // cache element  
  $(window).scroll(function(){
    var itemTop = $item.position().top-10;  // subtract some pixels from the  item 
    var winScrollTop =$(window).scrollTop();
    window.console && console.log(winScrollTop,itemTop); // remove when happy
    if  (winScrollTop>=itemTop) { 
      window.console && console.log("reached!",winScrollTop,itemTop); remove when happy
      $item.html("REACHED!");
    }
  });
}); 

and here for when it hits the bottom

Live Demo

$(function() {
  var $item = $(".results .item:last"); // cache element  
  $(window).scroll(function(){
    var itemTop = $item.position().top-10;  // subtract some pixels from the  item 
    var winScrollTop =$(window).scrollTop();
    var winHeight = $(window).height();  
    window.console && console.log(winScrollTop,itemTop); // remove when happy
    if  (winScrollTop+winHeight>=itemTop) { 
      window.console && console.log("reached!",winScrollTop,itemTop); // remove when happy
      $item.html("REACHED!");
    }
  });
}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM