4

i am currently learning jQuery. Problem: I have three component in the container. Initially all font color are black. I would like to change the font color according to the class name of each div.

I able to change two of them while fail to change all. My code are belows:

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.

1 Answer 1

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

Explanation:

  1. Loop through all divs inside container
  2. For each div, set the color to the class name after 1000 milliseconds multiplied by it's index in the set of divs
Sign up to request clarification or add additional context in comments.

21 Comments

don't create your own solution with unwanted functions from what the OP wanted. he might want to learn using delay.Also there can be olverlaps . your solution is NOT pure a then b then c. it's do a , calc time ( regardless a) and then do b. it's not the same
You should really know the difference between using setTimeout and .delay
don't create your own solution with unwanted functions from what the OP wanted. Unwanted functions? OP has asked for a solution, and didn't explicitly ask for the use of delay.
He had started with a very valid solution. you changed it completly for no reason. ( and incorrect one also)
You've mentioned the different between setTimeout and delay multiple times now. In this scenario, my useage of setTimeout is correct, your use of delay is unnecessary.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.