tags:

views:

173

answers:

1
 $('<div class="error"></div>').html('<h2>(click here to dismiss)</h2>').insertAfter($('#someid')).fadeIn('slow').animate({ opacity: 1.0 }, 1000).click(function() {
       $(this).fadeOut('slow', function() {
           $(this).remove()
       })
   });

is there a way to combine this with:

$('#someid').animate({opactiy: 1.0 } fadeOut('slow', function() {
            $(this).remove()
        });

in other words to combine it, so when they don't click it, it would still disappear after so many seconds..

+1  A: 

I'm not sure if there is a good way to chain all of that together so it happens in one command. You can use setTimeout on a separate line to achieve the same effect in another statement, however. For example, after your first statement:

setTimeout(function() {
    if ($('#someid').css('opacity') == 1.0) {
        // Fade out has not started yet
        $('#someid').animate({opactiy: 1.0 } fadeOut('slow', function() {
            $(this).remove()
        });
    }
}, 3000); // setTimeout counted in ms, not seconds

I agree that it might be more elegant to chain everything together, but I'm not aware of a good way to do that.

As a side note, you can have as much whitespace as you want between method names in Javascript, so you could break your original statement onto multiple lines for better readability, e.g.

$('<div class="error"></div>')
    .html('<h2>(click here to dismiss)</h2>')
    .insertAfter($('#someid'))
    .fadeIn('slow')
    .animate({ opacity: 1.0 }, 1000)
    .click(function() {
   $(this).fadeOut('slow', function() {
       $(this).remove()
   })

});

But that's a matter of preference.

Ryan