Search code examples
javascriptjqueryprepend

Only prepend after removed from end using jquery


I made this script which is working quite well. It gets a feed with a varying number of elements. Then if, for example, there are 5 elements it removes 5 from the end and prepends 5 to the start.

Unfortunately there seems to be a problem where it is not always waiting for the elements to be fully removed from the end before prepending them. This causes the footer to be bumped up and down.

I wonder if anyone knows how to fix my problem. I tried adding a delay but that only partially helped.

$(document).ready(function() {
    window.setInterval(function(){

        $.ajax({
            type: 'POST',
            url: location.protocol+'//'+location.hostname+'/index/feed',
            success: function(data) {

                var arr = data.split('@@@@@@@@@');

                $('#feed > .feed-item').slice(-1 * arr[0]).fadeOut(1000, function(){
                    $(this).remove();
                });

                $("#feed").delay(2000).prepend(arr[1]);

            }
        });

    },2000);
});

Solution

  • I had to change the code a little bit in order to make it work locally, but I think this example can give you a good grasp.

    I create a function: removeFeed(callback) that receives a function as a parameter, this function is invoked just after the remove statement.

    inside de success in $.ajax you create a anonymous function as the parameter for removeFeed and inside you put the prepend function.

    Hope it helps!

    $(document).ready(function() {
        var root = 'http://jsonplaceholder.typicode.com';
        var counter = 1;
    
        function removeFeed(callback) {
            $('#feed > .feed-item').fadeOut(1000, function() {
                $(this).remove();
                callback();
            });
        }
        window.setInterval(function() {
            $.ajax({
                url: root + '/posts/' + (counter + 1),
                method: 'GET',
                success: function(data) {
    
                    removeFeed(function() {
                        $("#feed").prepend("<li class='feed-item'>" + data.title + "</li>");
                    })
    
                }
            });
    
        }, 2000);
    });
    

    ps: it's fully functional, to see it working just copy and paste in a page.