Pregunta

I have a msg alert that shows up on select change or ajax request. It works partial ok but the issue is that if you switch between the options fast You will see fadeout/fadein again even the msg is already visible.

The desired effect is , if msg is visible and new msg comes in, clear existing timeout, set new msg timeout and than fade out. http://jsfiddle.net/p2979/1/

function alerts(msg) {

    $('.msg-alert').fadeIn(500).html(msg);

    if ($('.msg-alert').is(':visible')) {
        $('.msg-alert').delay(2000).fadeOut(500);
    }
}


$('#option').on('change', function () {


    if ($(this).val() == 1) {
        var msg = 'Msg 1';
    } else {
        msg = 'Msg 2';
    }

    alerts(msg);
});

Any help is appreciated. Thank you!

¿Fue útil?

Solución

You can use stop, and add function inside fadeOut() to add the html msg like this

function alerts(msg) {
    $('.msg-alert').stop().fadeOut(500, function () {
        $('.msg-alert').html(msg)
    }).fadeIn(500)
}

DEMO

Update

You can use clearInterval() and setTimeout like this

var tOut = null;

function alerts(msg) {
    clearTimeout(tOut);
    $this = $('.msg-alert');
    $this.html(msg).fadeIn(500);
    tOut = setTimeout(function () {
        $this.fadeOut(500);
    }, 2000);
}

DEMO

Otros consejos

Add .stop() before your .fadeIn() to clear the previous animation queue.

$('.msg-alert').stop().fadeIn(500).html(msg);

It usually takes care of all queueing quirks that happens when you are working with triggered animations.

And you can add your .fadeOut() to the callback of .fadeIn().

Demo

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top