Search code examples
jquerysetintervalevent-delegation

Remove Last occurance of dynamically created div


I have a div that I want to be able to add children to the top and remove child elements from the bottom from dynamically. Kinda like a rss ticker. The parent div is constantly populated with new children. There is a condition to test for the number of children, and then remove the last child once it reaches the max desired length of children. This is done with a setInterval() to be continuous.

setInterval(function(){
    var newbox = "<div class='child  animated bounceInDown'></div>"
    $(newbox).prependTo('#container').hide().slideDown(500);
    var dlength = $('.child').length;
    console.log(dlength);

    if (dlength >=5){
        $(".child:last").fadeOut();
     }
}, 2000);

Currently with my code, I can remove the last child div by using a counter populated with the max desired length of the parent div.

The problem is that it only removes the last div during the first interval. I log the count to the console and can see the count increment, so my condition should trigger.

My thought is that my problem is due to no event delegation. Essentially, the div isn't in the DOM when I try to remove it. That being said, I'm not sure if I need to listen for events on the parent or attach a handler. Any ideas?

Here is a fiddle example:

http://jsfiddle.net/luskbo/tcq8kuy6/9/


Solution

  • The problem is you are always fading out the last element in DOM, not the last visible element. As say, you are always fading the same element.

    $(".child:visible:last").fadeOut(); should to the trick.(It worked in the JSFiddle) Added :visible selector.

    Another option, as suggested by Anant, is to remove the element from the DOM instead of just fading it out, it depends on what you may want to achieve. If you dont need the element to remain in the DOM, maybe it would be a good practice to remove it.

    $(".child:visible:last").fadeOut(400,function(){
      $(this).remove();
    });