1

I'm currently trying to build my javascript function that gives css styles to every character in an element. Specifically, this function takes in an element, takes the text content in it, stores the text into an array and then create a bunch of spans to append to the text. Right now it seems like my code runs and when I check the variables in chrome dev tools, they return the correct values. However, when I actually implement this code, nothing changes visually but in the dev tools, I get my correct value of <span style="style i chose" > text </span>. Not sure what I did wrong here

var array = [];
var spanarray = [];
var words = document.getElementsByClassName("example")[0];
function fadeInByLetter () {
        for(var i = 0; i < words.innerHTML.length;i++){
            array.push(words.innerHTML[i]);
            var span = document.createElement("span");
            var textNode = document.createTextNode(array[i]);
            span.appendChild(textNode);
            var spancomplete = span;
            spanarray.push(spancomplete);

        }

        for(var i = 0; i < array.length;i++){
            spanarray[i].style.color = "red";
            spanarray[i].style.background = "pink";
        }

    }    

fadeInByLetter();
3
  • You're not replacing innerHTML with new content ;) Commented Aug 10, 2017 at 19:50
  • where are you putting the span elements into the DOM? Commented Aug 10, 2017 at 19:51
  • where do you want to put the letters? try to append or set the span content in a DOM. Commented Aug 10, 2017 at 19:53

3 Answers 3

0
var array = [];
var spanarray = [];
var words = document.getElementsByClassName("example")[0];
function fadeInByLetter () {
    for(var i = 0; i < words.innerHTML.length;i++){
        array.push(words.innerHTML[i]);
        var span = document.createElement("span");
        var textNode = document.createTextNode(array[i]);
        span.appendChild(textNode);
        var spancomplete = span;
        spanarray.push(spancomplete);

    }
    words.innerHTML="";
    for(var i = 0; i < array.length;i++){
        spanarray[i].style.color = "red";
        spanarray[i].style.background = "pink";
        words.appendChild(spanarray[i]);
    }

}    

fadeInByLetter();

The solution above should fix the problem. However you have some performance issues. You should save words.innerHTML in a string first. Then use the string instead of words.innerHTML.

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

Comments

0

That should do the trick:

function fadeInByLetter (wordsContainer) {
    // extract text from the container and transform into array
    var chars = wordsContainer.innerHTML.split('')
    //clear the container
    while (wordsContainer.firstChild) {
        wordsContainer.removeChild(wordsContainer.firstChild);
    }

    for(var i = 0; i < chars.length;i++){
        var span = document.createElement("span");
        var textNode = document.createTextNode(chars[i]);
        span.appendChild(textNode);
        span.style.color = "red";
        span.style.background = "pink";
        // append new element
        wordsContainer.appendChild(span)
    }
}    

fadeInByLetter(document.getElementsByClassName("example")[0]);

Comments

0

FYI: There is a library that does this same type of thing. It's called lettering https://github.com/davatron5000/Lettering.js

Here is a demo using this library.

The library depends upon jQuery but there is also a version of this lib that uses plain javascript. See https://github.com/davatron5000/Lettering.js/wiki/More-Lettering.js

$(document).ready(function() {
  $(".example").lettering();
});

//////////////// LETTERING SOURCE BELOW /////////////////////////////
//fadeInByLetter();
/*global jQuery */
/*!
 * Lettering.JS 0.7.0
 *
 * Copyright 2010, Dave Rupert http://daverupert.com
 * Released under the WTFPL license
 * http://sam.zoy.org/wtfpl/
 *
 * Thanks to Paul Irish - http://paulirish.com - for the feedback.
 *
 * Date: Mon Sep 20 17:14:00 2010 -0600
 */
(function($) {
  function injector(t, splitter, klass, after) {
    var text = t.text(),
      a = text.split(splitter),
      inject = '';
    if (a.length) {
      $(a).each(function(i, item) {
        inject += '<span class="' + klass + (i + 1) + '" aria-hidden="true">' + item + '</span>' + after;
      });
      t.attr('aria-label', text)
        .empty()
        .append(inject)

    }
  }


  var methods = {
    init: function() {

      return this.each(function() {
        injector($(this), '', 'char', '');
      });

    },

    words: function() {

      return this.each(function() {
        injector($(this), ' ', 'word', ' ');
      });

    },

    lines: function() {

      return this.each(function() {
        var r = "eefec303079ad17405c889e092e105b0";
        // Because it's hard to split a <br/> tag consistently across browsers,
        // (*ahem* IE *ahem*), we replace all <br/> instances with an md5 hash
        // (of the word "split").  If you're trying to use this plugin on that
        // md5 hash string, it will fail because you're being ridiculous.
        injector($(this).children("br").replaceWith(r).end(), r, 'line', '');
      });

    }
  };

  $.fn.lettering = function(method) {
    // Method calling logic
    if (method && methods[method]) {
      return methods[method].apply(this, [].slice.call(arguments, 1));
    } else if (method === 'letters' || !method) {
      return methods.init.apply(this, [].slice.call(arguments, 0)); // always pass an array
    }
    $.error('Method ' + method + ' does not exist on jQuery.lettering');
    return this;
  };

})(jQuery);
span {
  font-size: 74px;
  font-family: Arial;
  font-weight: 600;
  text-transform: uppercase;
  letter-spacing: 11px;
  display: inline-block;
}

.char1 {
  color: red;
  transform: rotateZ(-10deg);
}

.char2 {
  color: blue;
  transform: rotateZ(-12deg);
}

.char3 {
  color: purple;
  transform: rotateZ(12deg);
}

.char4 {
  color: pink;
  transform: rotateZ(-22deg);
}

.char5 {
  color: yellow;
  transform: rotateZ(-12deg);
}

.char6 {
  color: gray;
  transform: rotateZ(22deg);
}

.char7 {
  color: orange;
  transform: rotateZ(10deg);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="example">Example</span>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.