Question

i have next jq script:

setInterval(function(){
  $("#box div:last-child").fadeOut(200);
  $.post('_ajax.php',function(mr){
    $("#box").prepend(mr);
  });
}, 1000);

and next html:

<div id="box">
   <div>23:56:16<span>xxxx</span></div>
   <div>23:56:16<span>xxxx</span></div>
   <div>23:56:16<span>xxxx</span></div>
   <div>23:56:16<span>xxxx</span></div>
</div>

So, i need to remove last <div> from #box every second and .prepend new div which i get via ajax. But this code works only on first second. I.e. after 1 second from page loading last <div> from #box removed, but next time just .prepend works.

Also, i need to know how i can remove several last child div's.

Was it helpful?

Solution

The problem if you're fading out the element and not removing it. Every subsequent time it gets the element, it's fading out the already faded out element. Try this. Add the complete callback to the fade and remove the element from the DOM.

setInterval(function(){
  $("#box div:last-child").fadeOut(200, function() { $(this).remove(); });
  $.post('_ajax.php',function(mr){
    $("#box").prepend(mr);
  });
}, 1000);

Also, as j08691 pointed out in his comment, $.post is anynchronous, meaning the request may or may not complete itself in that 1 second. If it's slow, you'll be removing elements without appending any. You might consider fading out the element only when you're ready to append the new one like this:

setInterval(function(){
      $.post('_ajax.php',function(mr){
        $("#box div:last-child").fadeOut(200, function() { $(this).remove(); });
        $("#box").prepend(mr);
      });
    }, 1000);

If you're interested in removing a certain number of elements from the end of the box, you could do the following:

$("#box div").slice(-3).remove();

You can read about .slice here http://api.jquery.com/slice/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top