user007
user007

Reputation: 3243

jQuery - delay and fadeout before remove

I am trying to do a .delay() and .fadeOut() then .remove()

But delay and fadeout has no effect in remove

Here is my code:

jQuery("#container").delegate(".remove", "click", function (e) {
    e.preventDefault();
    var parent = jQuery(this).data('parent');
    jQuery(this).closest('.' + parent).fadeOut(1000).delay(1000).remove();
})

Upvotes: 3

Views: 5650

Answers (4)

kasskata
kasskata

Reputation: 1

I create simple function for my project. I use Bootstrap alerts, but the last row answer your question: $('#some-tag').fadeIn().delay(3000).fadeOut('slow',function(){$(this).remove();});

 function alertFade(type,message){
    //alerts: info, warning, success, danger
    var $div = $('<div id="addSuccess" class="alert alert-'+type+'">'+message+'</div>');
    $('#alerts').append($('<div id="addSuccess" class="alert alert-'+type+'">'+message+'</div>'));
    $('#alerts').children().fadeIn().delay(3000).fadeOut('slow',function(){$(this).remove();});
}

Upvotes: 0

Spokey
Spokey

Reputation: 10994

.remove() is not in a query nor is it a transition so .delay() will not work. Use setTimeout instead.

jQuery(this).closest('.' + parent).fadeOut(1000, function(){
   setTimeout($(this).remove(), 1000)
});

A side note, use .on() instead of .delegate() with the newer versions of jQuery

Upvotes: 2

Arun P Johny
Arun P Johny

Reputation: 388316

why not

jQuery(this).closest('.' + parent).fadeOut(1000, function(){
    $(this).remove()
});

You should make use of the complete callback provided by .fadeOut() in this case

jQuery("#container").on("click", ".remove", function (e) {
    e.preventDefault();
    var $this = jQuery(this), parent = $this.data('parent');
    $this.closest('.' + parent).fadeOut(1000).delay(1000).remove();
})

Upvotes: 9

Techie
Techie

Reputation: 45124

You can do something like below

jQuery("#container").delegate(".remove", "click", function (e) {
    e.preventDefault();
    var parent = jQuery(this).data('parent');
    //jQuery(this).closest('.' + parent).fadeOut(1000).delay(1000).remove();

    jQuery(this).closest('.' + parent).delay(1000).fadeOut(1000, function(){
      $(this).remove();
    });
})

Read the below link to find out about other methods of doing this.

Why can't I delay a remove call with jQuery

Advice

Try using .on() instead of using .delegate()

Upvotes: 2

Related Questions