Random Colorful letters

Viewed 318

I have this code:

<div  id="list" rows="10"></div>
<script>
 $(function() {
   setTime();
   function setTime() {
       $.ajax({
            url : "../abc.php",
            dataType: "text",
            success : function (result) {
                $("#list").html(result);
            }           
        });
      var date = new Date().getTime();
      setTimeout(setTime, 3000);
      $('#list').html(result);
      //Here  should call a function to color all the words of the div
   }


    });
</script>

    });

I'm trying to color all letters every 3 seconds using the setTime () function.

Note: I'm trying to color each letter of a word, in other words, each letter will have a color

Like:

https://i.imgur.com/Tw2Q58U.png

I tried with this code, but it changes the color of the entire div(The div stay with only one color):

var randomColor = Math.floor(Math.random()*16777215).toString(16);
document.getElementById('list').style.color = '#' + randomColor

4 Answers

You would have to break your text into children spans and do the coloring on them.

function colorElement(element) {
  var randomColor = Math.floor(Math.random()*16777215).toString(16);
  element.style.color = '#' + randomColor;
}

function splitElement(element) {
  var text = element.innerText;
  element.innerText = '';
  var chars = text.split('');
  for(var ch of chars) {
     var charSpan = document.createElement('span');
     charSpan.innerText = ch;
     element.appendChild(charSpan);
  }
}

function randomColor() {
   var result = document.querySelectorAll('span span');
   for(ele of result){
      colorElement(ele);
   }
}

var ele = document.getElementById('myText');
splitElement(ele);
setInterval(function() {
   randomColor();
},500);
<div>
  <span id="myText">Disco Text</span>
</div>

If you want to get only vivid colors, using randomness like this wont do.

What you need is a function for HSV to RGB conversion, like this:

function HSVtoRGB(h, s, v)
{
    var r, g, b, i, f, p, q, t;
    i = Math.floor(h * 6);
    f = h * 6 - i;
    p = v * (1 - s);
    q = v * (1 - f * s);
    t = v * (1 - (1 - f) * s);
    switch (i % 6)
    {
        case 0: r = v, g = t, b = p; break;
        case 1: r = q, g = v, b = p; break;
        case 2: r = p, g = v, b = t; break;
        case 3: r = p, g = q, b = v; break;
        case 4: r = t, g = p, b = v; break;
        case 5: r = v, g = p, b = q; break;
    }
    r = Math.round(r * 255).toString(16);
    g = Math.round(g * 255).toString(16);
    b = Math.round(b * 255).toString(16);
    if (r.length < 2) r = '0' + r;
    if (g.length < 2) g = '0' + g;
    if (b.length < 2) b = '0' + b;

    return '#' + r + g + b;
}

Parameters range from 0 to 1. Using HSVtoRGB(Math.random(), 1, 1) will always yield you a vivid color with maximum value and saturation.

ok, I try this, it exactly working like you are asking. You can use it in your code.

 window.setInterval(function(){
    changeLetterColor();
        }, 3000);



    function changeLetterColor(){
    var string = "hello world";
    var customstring ='';
    for(var i =0;i<string.length;i++){
    customstring += "<span font color= '#"+Math.floor(100000 + Math.random() * 900000)+"'>"+ string[i]+" </span>";
    }

    }

If result is a text then you need to wrap each letter with span.. do like code below:

<div  id="list" rows="10"></div>
<script>
  $(function() {
    setTime();
    function setTime() {
        $.ajax({
             url : "../abc.php",
             dataType: "text",
             success : function (result) {
                  $("#list").html(result);
                  $("#list")
                  .contents()
                  .filter(function(){
                    return this.nodeType !== 1;
                  })
                  .wrap( "<b class='colorful_text'></b>" );
                   $.each($(".colorful_text"), function(o, v){

                      var textEle = $(this).text()
                      console.log("textEle", textEle)
                      $(this).html("")
                      for(var n=0; n<textEle.length; n++) {
                            var randomColor = Math.floor(Math.random()*16777215).toString(16);
                            var color = '#' + randomColor
                            var ele = document.createElement("span")
                            ele.style.color = color
                            ele.innerText = textEle[n]        

                            $(this).append(ele)

                      }

                })
             }           
        });
       var date = new Date().getTime();
       setTimeout(setTime, 3000);
       $("#list").html();

       //Here  should call a function to color all the words of the div
    }

});
</script>
Related