1

Im creating a function to make text a rainbow color.

I have two arrays. One for color and one for a string.

What I'm basically trying to do is loop over the colors as many times needed depending on how much text there are.

var colors = ['blue', 'red', 'green', 'black', 'orange', 'purple'];

function colorText(word) {
  var slicedText = word.split('');
  var rainbowText= '';
  
  if (typeof(word) !== 'string') {
    alert('Thats not a word!');
  } else {
    for (var i = 0; i < slicedText.length; i++ ) {
      rainbowText += '<span style="color:' + colors[i] + ';">' + slicedText[i] + '</span>';
  }
  
  document.getElementById('text-input').innerHTML = rainbowText;
  }
}

colorText('this is a really long text');
<div id="text-input">
  
</div>

1
  • Change this line rainbowText += '<span style="color:' + colors[i % colors.length] + ';">' + slicedText[i] + '</span>'; Commented Oct 11, 2016 at 23:26

2 Answers 2

4

You are indexing outside the bounds of the array of colors when the slicedText.length is greater than colors.length. If the desired behavior is to start at index 0 after it reaches the end of the colors, use the modulo operator.

colors[ i % colors.length ]

var colors = [ 'blue', 'red', 'green', 'black', 'orange', 'purple' ];

function colorText(word) {
  var slicedText = word.split( '' );
  var rainbowText = '';

  if (typeof( word ) !== 'string') {
    alert('Thats not a word!');
  } else {
    for (var i = 0; i < slicedText.length; i++) {
      rainbowText += '<span style="color:' + colors[ i % colors.length ] + ';">' + slicedText[ i ] + '</span>';
    }

    document.getElementById( 'text-input' ).innerHTML = rainbowText;
  }
}

colorText( 'this is a really long text' );
<div id="text-input">
  
</div>

Sign up to request clarification or add additional context in comments.

Comments

0

Another way of implementing the same job without coloring the white spaces.

var str = "this is a really long text",
 colors = ['blue', 'red', 'green', 'black', 'orange', 'purple'],
 result = [...Array(str.length)].reduce((p,_,i) => p + (str[i] !== ' ' ? '<span style="color:'+colors[i%colors.length]+';">' + str[i] + '</span>'
                                                                       : ' '),'');
document.getElementById("textdiv").innerHTML = result;
<div id="textdiv"></div>

Comments

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.