jen hill
jen hill

Reputation: 27

change the font of a string one character at a time

if i give each character its own #id, i understand how to change the font-style one character at a time, however, i hope to do this for whole webpages. is there a more efficient way? or is making hundreds of #ids a viable option?

<body>
    <div>
        <p> Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p> 
    </div>

    <script src="jquery.js" type="text/javascript" ></script>   

    <script>
        var text = $("p").text();
        var newText = [];
        for (var i = 0; i < text.length; i++) {
            newText.push(text[i]);
            // ???????? function goes here ????????
        }
    </script>
</body>

ultimately, what i think i need to do is make each character string into an HTML object ? is this possible ?

Upvotes: 3

Views: 1696

Answers (2)

Akshay Gohil
Akshay Gohil

Reputation: 382

HTML

<h1 id='name'>HULK IS GETTING ANGRY</h1>

JS

$(document).ready(function(){
  var name = $('#name').text();
  var i = 0;

  function changeColor () {
    setTimeout(function () {
      var firstPart = name.substr(0,i);
      var secondPart = name.substr(i,name.length);
      var newHtml = '<span style="color:green; font-family: \'Comic Sans MS\';">'+firstPart+'</span>'+secondPart;

      if (i < name.length) { 
        changeColor();
      }
      i++;
    }, 500);
  }
  changeColor();
});

Check out this code-pen snippet

Upvotes: 0

Matthias Knoll
Matthias Knoll

Reputation: 99

Convert the text into an array, iterate over it and wrap every char in a <span>-tag and apply a class to it that specifies the font.

var text = $('p').text().split('');

text = text.map(function (char) {

    // you probably don't want to wrap spaces
    if (char === ' ') {
        return char;
    }

    return '<span class="comicSans">'+char+'</span>';
});

// convert the array back into a string
text = text.join('');

// replace the original string with the new 'fancy' string
$('p').text(text);

style.css

.comicSans {
  font-family: "Comic Sans";
}

Upvotes: 2

Related Questions