1

I want to make a page that has each letter individually and randomly colored. The way I'm thinking of doing this is to put a span and /span tag around each letter and give the span a style attribute equivalent to the css color property with a random rgb value.

Is this a "good" way? Is there a better way? I put good in quotes because t r here doesn't seem to be any elegant way to do this to me.

Thanks!

Bunny
  • 192
  • 1
  • 1
  • 14
  • That seems to be the _only way_ – Rayon Apr 30 '16 at 03:16
  • Related: http://stackoverflow.com/questions/17341670/change-color-of-one-character-in-a-text-box-html-css (tldr: can't do it without extra elements) – Ben Apr 30 '16 at 03:17
  • Styles can only be applied to HTML elements (tags), not to portions of the content within a tag. So there's no way to color each letter differently via a style unless each letter is contained in its own tag. – RJM Apr 30 '16 at 03:26
  • The following question asks to do exactly the same thing with jQuery, but the accepted answer does it with (mostly) vanilla JS: http://stackoverflow.com/questions/9452340/iterating-through-each-text-element-in-a-page - you'd just need to tweak it to set the colours. – nnnnnn Apr 30 '16 at 03:26

3 Answers3

1

use lettering.js http://letteringjs.com/

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script src="_scripts/jquery.lettering.js"></script>
 <script>
  $(document).ready(function() {
    $(".classname").lettering();
  });
</script>

you can download the lettering.js

This will break the text in the class into span with unique classes which you can then target later

Dhaval Chheda
  • 4,637
  • 5
  • 24
  • 44
1

with jquery: https://jsfiddle.net/geLrvur3/3/

$(function(){
$('p').each(function(index, element) {
    var $el = $(element);
    var words = $el.text().split(' ').join('').split(' ').join('');
    $el.html('');
    for (var i = 0; i < words.length; i++) {
      var newSpan = $('<span>').text(words[i] + ' ');
      $el.append(newSpan);
    }
  });

  setInterval(function() {
    $('span').each(function(){
      var red   = Math.floor(Math.random() * 256);
      var green = Math.floor(Math.random() * 256);
      var blue  = Math.floor(Math.random() * 256);
      $(this).css('color', 'rgb(' + red + ',' + green + ',' + blue + ')');
    });
  }, 500);
});
omarjmh
  • 13,632
  • 6
  • 34
  • 42
0

Using jQuery you can do something like this:

var text = "hello hello hello world";
var letters = text.split(''); 
letters.forEach(function(letter){
  $('body').append($('<span>').text(letter)
    .css('color', '#' + Math.floor(Math.random() * 16777216).toString(16)));
});
Max Kroshka
  • 457
  • 2
  • 5