Mr. Jo
Mr. Jo

Reputation: 5261

JQuery add and remove class chained with delay not working

I have this function:

jQuery(document).ready(function ()
{
    jQuery('.current-visitors').delay(3000).queue(function ()
    {
        jQuery(this).addClass('show').delay(1000).queue(function ()
        {
            jQuery(this).removeClass('show');
        });
    });
});

So I've tried to add a class after 3 seconds which works great. Then I set a new delay and queue a new method for remove the class, so after 1 second the class should be removed, but this last part isn't working. What is wrong?

Upvotes: 1

Views: 216

Answers (3)

Shidersz
Shidersz

Reputation: 17190

You can do it with the queue() method, but you had a wrong chaining approach, and also you forgot to call the dequeue() method on every function you was queueing, so the next function on the chain is executed.

I have increased the delay for hide the element a little, but you can check it working on the next snippet example:

jQuery(document).ready(function()
{
    jQuery('.current-visitors').delay(3000).queue(function()
    {
        console.log("Now visible!")
        $(this).addClass("show").dequeue();            
    })
    .delay(3000).queue(function()
    {
        console.log("Now hidden!")
        $(this).removeClass("show").dequeue();
    });
});
.current-visitors {
    background: lightblue;
    display: none;
}

.show {
    display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="current-visitors">CURRENT VISITORS</div>

Upvotes: 1

Mr. Jo
Mr. Jo

Reputation: 5261

This is also a minimal working solution:

jQuery('.current-visitors').delay(3000).queue(function () {
        jQuery(this).addClass('show');

        setTimeout(function () {
            jQuery('.current-visitors').removeClass('show');
        }, 6000);
    });

Upvotes: 0

Kubwimana Adrien
Kubwimana Adrien

Reputation: 2531

If you need something simple I have created a simple jQuery snippet for you:

jQuery.fn.wait = function(seconds){
    var element = this, deferred = jQuery.Deferred();
    setTimeout(function(){
        deferred.resolve.apply(element);
    }, seconds);

    return deferred;
}

jQuery(document).ready(function () {
    jQuery('.current-visitors').wait(3000).then(function () {
        jQuery(this).addClass('show').wait(1000).then(function () {
            jQuery(this).removeClass('show')
        });
    });
});

Upvotes: 0

Related Questions