Using jQuery.filter

I am currently studying jQuery. Problem: I have three components in a container. Initially, all font color is black. I would like to change the font color according to the class name for each div.

I can change two of them until I can change everything. My code is:

index.html

<!DOCTYPE html>
<html>
<head>

</head>
<body>
    <div class="container">
        <div class="Red">old content</div>
        <div class="Black">old content</div>
        <div class="Blue">old content</div>
    </div>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="index.js"></script>

</body>
</html>

index.js

$(document).ready(function(){
    $('.container div')
        .delay(10000)
        .css("color","Blue")
        .delay(10000)
        .filter(".Red")
        .css("color", "Red")
        .delay(10000)
        .filter(".Black")
        .css("color", "Black");
    });

Please advice.

+4
source share
1 answer
$('.container div').each(function(i, el)
{
    setTimeout(function(){
       $(this).css("color", $(this).attr('class'));
    }, i * 1000);
});

Explanation:

  • Loop through all divs inside a container
  • For each div, set the color of the class name after 1000 milliseconds times the index in the set of divs
+1
source

All Articles