JQuery Callback at the end of page scroll

I have a div tag that is set to overflow: scroll in css.
I have a callback that is supposed to be called at the end of the scroll of an element that is found using this.

$('#details').scroll( function () {  
    if ($(this).height() == ($(this).get(0).scrollHeight - $(this).scrollTop())) {  
        getDetails($("span:last").attr("id"), 3);  
    }  
});  

      

where getDetails is the callback call im. it takes the last span element inside the div and sends it as value. it's all ajax calls. The problem is getDetails gets three times every time I hover to the end of the div. any suggestions on how i can call it once?

The repeated callback only happens when I use the scroll wheel or press the scroll bar down button. Everything works fine when the scrollbar is moved.

+3


source to share


2 answers


I haven't tested this, but something like that might work. Its pretty khaki though ...



$('#details').data("didfire", false).scroll( function () {  
    if ($(this).height() == ($(this).get(0).scrollHeight - $(this).scrollTop())) {  
        if(!$(this).data("didfire")) {
            getDetails($("span:last").attr("id"), 3);  

            $(this).data("didfire", true)
            var ref = $(this);
            setTimeout(function(){
                ref.data("didfire", false);
            }, 500);
        }
    }  
}); 

      

+2


source


You should defer handling events with constant feedback, such as scrolling and resizing using setTimeout

/ clearTimeout

. When the event you want to handle is raised, invoke your intended handler in setTimeout with a reasonable duration, but keep a reference to the returned setTimeout handle. Now modify this same code to check for the existence of this descriptor, and if it exists, clearTimeout

and update the descriptor for a new call to setTimeout.

Here's a working example: http://jsfiddle.net/SBgXA/



       var timeoutHandle;

       var handler =  function(e) {
              alert('raised'); // put your code here
              if ($(this).height() == ($(this).get(0).scrollHeight - $(this).scrollTop()) {  
                getDetails($("span:last").attr("id"), 3);  
              }
       }

       $('#details').scroll(function(e) {
           clearTimeout(timeoutHandle);

           timeoutHandle = setTimeout(function() {
             handler(e);
           }, 100);
       });

      

+4


source







All Articles