Hailwood
Hailwood

Reputation: 92581

jquery : show/hide div, timing

I have a pretty standard problem here.

I have an error div that,

when a button is pressed is populated with an error message, the div is then faded in, after (500*n)ms (where n = number of letters) the div is faded out.

my issue occurs when the user presses the button again before the div has faded out.

while the div is still visible the divs contents are updated with the new error message,

after the initial (500*n)ms the div is faded out, then immediately gets faded back in and is visible for another (500*n)ms.

What I want is.

How can I achieve this?

My current code is below

function login_error(message){
        $('form').effect('shake', { times: 1 }, 50);
        $('#error').html(message).fadeIn('fast').delay(500*message.length).fadeOut('fast');
}

Upvotes: 0

Views: 802

Answers (3)

Andy
Andy

Reputation: 30135

simething like this?

 $(function() {
    var counter = 0;
    var timeOut;
    $('button').click(function() {
        showdiv('clicked ' + counter++);
    });

    function showdiv(str) {
        clearTimeout(timeOut);
        $('div').fadeOut(function() {
            $(this).html(str).fadeIn(function() {
                timeOut = setTimeout(function() {
                    $('div').fadeOut();
                }, 100 * str.length);
            });
        })
    }
});

demo: http://www.jsfiddle.net/N88gv/

Upvotes: 1

mr.b
mr.b

Reputation: 2708

Another solution would be that after clicking the button you can disable it and with the div finishes/the animation is done you can enable it back.

Upvotes: 0

Malk
Malk

Reputation: 11983

Perhaps if you stop the animation and reset the div

  $('#error').stop().hide().html(message).fadeIn('fast').delay(500*message.length).fadeOut('fast');

Upvotes: 0

Related Questions