Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery add a class after a delay then delay and a another class

Tags:

jquery

css

How do I add a class after a delay then delay and a another class?

I can only seem to add one.

$(document).ready(function() {
    $(".websites-container").delay(5000).queue(function() {
            $(this).addClass("active");
    });

    $(".websites-container").delay(8000).queue(function() {
            $(this).addClass("gone")
    });
});
like image 563
MrThunder Avatar asked Jun 07 '15 20:06

MrThunder


2 Answers

You need to call .dequeue() in the .queue() callback, otherwise the following items in the queue never get executed.

$(document).ready(function() {
    $(".websites-container").delay(1000).queue(function() {
            // I'm impatient. I shortened the times.
            $(this).addClass("active").dequeue();
    }).delay(2000).queue(function() {
            $(this).addClass("gone");
    });
});
.active {font-weight: bold}
.gone {color:red}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="websites-container">abc</div>

(This was almost solved by @adeneo, with the exception of placing dequeue in the callback.)

like image 178
Scimonster Avatar answered Oct 07 '22 01:10

Scimonster


Most likely the issue you're having is that you're using jQuery's delay feature incorrectly. Take a look at this SO question for reference: .delay() and .setTimeout()

Since we're not working with an animation or within an already existing jQuery queue you should be using setTimeout in most cases:

$(document).ready(function() {
    window.setTimeout(function() {
        $(".websites-container").addClass("active");
    }, 5000);

    window.setTimeout(function() {
        $(".websites-container").addClass("gone");
    }, 8000);
});
like image 45
JNYRanger Avatar answered Oct 07 '22 01:10

JNYRanger