-1

I have some text on my website written in HTML:

<h2 class="sub">Here is <span id="my_words">word1</span>.</h2>

I currently have JavaScript written that makes the word change dynamically on the site:

$(function () {
    count = 0;
    wordsArray = ["word1", "word2", "word3"];
    setInterval(function () {
        count++;
        $("#my_words").fadeOut(1000, function () {
            $(this).text(wordsArray[count % wordsArray.length]).fadeIn(1000);
        });
    }, 2000);
});

How can I make it so that the color of the word changes each time it cycles? Either from pre-defined colors or randomly.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
user1551817
  • 6,693
  • 22
  • 72
  • 109
  • `$(this).css('color', getRandomColor()).text(...).fadeIn(...)`? Just write `getRandomColor` like every other question regarding getting a random color we have on the site. – Heretic Monkey Nov 19 '20 at 13:53
  • Does this answer your question? [Random color generator](https://stackoverflow.com/questions/1484506/random-color-generator) – Heretic Monkey Nov 19 '20 at 13:55

1 Answers1

1

You can change the color of span using $.css jquery function as follows.

$(function () {
    count = 0;
    wordsArray = ["word1", "word2", "word3"];
    
    const colorArray = [ '#FF0000', '#00FF00', '#0000FF' ];
    setInterval(function () {
        count++;
        $("#my_words").fadeOut(1000, function () {
            $(this).text(wordsArray[count % wordsArray.length]).fadeIn(1000);
            $(this).css('color', colorArray[count % colorArray.length]).fadeIn(1000);
        });
    }, 2000);
});
<h2 class="sub">Here is <span id="my_words">word1</span>.</h2>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Derek Wang
  • 10,098
  • 4
  • 18
  • 39