jquery fadeOut on future element

85 views Asked by At

is there posibility to apply jquery fadeOut on element which will be inserted into DOM later via ajax? I can apply clasic event via .on, but not sure how to make it with element ready.

    $(document).on('ready','.flash',function(){
    $('.flash').delay(200).fadeOut();
})

Im trying something like this but without succes.

1

There are 1 answers

0
Leeish On

On page load $('.flash') doesn't exist. So you'd need to either have an event fire to trigger this, or I would imagine a timeout would work, but I would go with the event method.

setTimeout(fuction(){$('.flash').fadeOut();},200);

The better option is only attempt to fade out when something happens. So when a user does X that makes flash appear, then you fade it out, but without knowing your use case and code it's just conjecture.

For our flash object we actually have the element in the DOM always. Our AJAX and other calls simply modify it. I have a showFlash(msg,type,ttl) method that when called, sets the content, type, and time to live whenever I want. To technically the flash is always in the DOM.

I then have

$.ajax({/*AJAX STUFF*/,
    complete: function(data){
    /* DO STUFF */
    showFlash('Message to User','success',3000);
}

function showFlash(msg,type,ttl){
    $('.flash').html(msg).show().delay(ttl).fadeOut();
}

In a nutshell that's it.