0

i've done a simple code that when i scroll down i load more data and i append new div to a parent div..when i reach a number of div that i had appended i remove previous div, it works quite well except for the fact that the app keep the scroll to the last element, so if i reach element 20, i load other 10 elements at the bottom but i remove 10 elements at the top so the user jump from element 20 to element 30.

here's my code:

 $(window).scroll(function() {
   if($(window).scrollTop() + $(window).height() == $(document).height()) {
       var divvo=document.getElementById("content");
       var ultimo;
       for(var i=0;i<=9;i++){

       if(i+window.count<=window.gvariabile.length){
       var div = document.createElement('div');
       div.setAttribute('class', 'ccc'); 
       var ccc=i+window.count;
       div.setAttribute('id', 'd'+ccc); 
       //alert(i+window.count);
       div.innerHTML="<img src='img/eng_ico.jpg' class='logo'> <h3>"+window.gvariabile[i+window.count]+"</h3><p>Dettagli</p><hr class='hor'>";
       div.addEventListener("click", redirect_click(i+window.count), false);
       ultimo=ccc;
       divvo.appendChild(div);    
           }
       }
       alert($(window).scrollTop());
       if(window.count>=20)
       {
       alert("cancella");
       var parente=document.getElementById("content");
       for(var k=0;k<=9;k++){
           var rem=(window.count-20);
           var rem2=rem+k;

           var divvv = document.getElementById("d"+rem2);

           parente.removeChild(divvv);
           }

       }
      // window.scroll(0,findPos(document.getElementById("d"+ultimo+"")));
       window.count=window.count+10;

   }
});

and then the html where i append:

<div id="content">
<div class="background"></div> 
 </div>

1 Answer 1

0

Solved by saving the scroll before deleting elements and set the scroll after deleting the elements:

 var scrollino=$(window).scrollTop();

       if(window.count>=20)
       {

       var parente=document.getElementById("content");
       for(var k=0;k<=9;k++){
           var rem=(window.count-20);
           var rem2=rem+k;

           var divvv = document.getElementById("d"+rem2);

           parente.removeChild(divvv);
           }
       window.scroll(0,scrollino);
       }

       window.count=window.count+10;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.