How to add fade out after few seconds in append content in javascript

100 Views Asked by At

first of all, I am not sure how to ask this properly. I hope you can understand based on the piece of code I provide below.

The code below basically appends every new content from bottom to top. I would like to make every new content to fade out after a few seconds. So that means, once every new content appear, it will fade out after few seconds.

function addContent(payload) {
    // Container
    let content = $('#paper');
    content.append("<div class='item'>" + payload + "</div></br>");

    // Scroll top bottom
    content.animate({ scrollTop: content.get(0).scrollHeight }, 333);
}

I found this code .fadeIn('fast').delay(5000).fadeOut('fast') somewhere on the internet but I don't know how to use it with the code I have up there.

1

There are 1 best solutions below

0
baxsm On BEST ANSWER

Code:

function addContent(payload) {
    // Container
    let content = $('#paper');
    $("<div class='item'>" + payload + "</div></br>").appendTo(content).fadeOut(500);
    // Scroll top bottom
    content.animate({ scrollTop: content.get(0).scrollHeight }, 333);
}

Explanation:

While using JQuery you need to first Select an element and than apply the respective function to it.

So first we select the element which is $("<div class='item'>" + payload + "</div></br>") and then append it into the appropriate place which will become $("<div class='item'>" + payload + "</div></br>").appendTo(content) Creating New Elements

Then we will apply the fadeOut function to our New Element and the final result will be $("<div class='item'>" + payload + "</div></br>").appendTo(content).fadeOut(); More details about fadeOut

JQuery applies the method to what is Selected.