Color Loop in Text

10

I have the following structure in HTML:

<font class="a">J</font>
<font class="b">o</font>
<font class="c">ã</font>
<font class="d">o</font>
<font class="e">P</font>
<font class="f">a</font>
<font class="g">u</font>
<font class="g">l</font>
<font class="i">o</font>
<font class="j">S</font>
<font class="l">a</font>
<font class="m">r</font>
<font class="n">a</font>
<font class="o">g</font>
<font class="p">o</font>
<font class="q">s</font>
<font class="r">s</font>
<font class="s">a</font>

And a JQuery that changes the color of each font:

setInterval(function()
{
    var cores = 
    [
        "#ff00ff",
        "#ff00cc",
        "#ff0099",
        "#ff0066",
        "#ff0033",
        "#ff0000",
        "#ff3300",
        "#ff6600",
        "#ff9900",
        "#ffcc00",
        "#ffff00",
        "#ccff00",
        "#99ff00",
        "#66ff00",
        "#33ff00",
        "#00ff00",
        "#00ff33",
        "#00ff66"
    ]

    letras =
    [
        "a","b","c","d","e","f","g","h","i","j","l","m","n","o","p","q","r","s"
    ]

    for (var i = 0; i <= cores.length; i++) 
    {
        $("font[class ="+letras[i]+"]").css('color', cores[i]);
    }
},500);

How can I create a loop that changes the color of the letters in a time interval, so that at each interval each letter receives the previous color it had received in the previous loop?

Code

    
asked by anonymous 06.03.2014 / 14:48

4 answers

9

You do not need to use <font> , which is obsolete . Prefer to use <span> tags. But you do not even have to use so many classes and elements, it's easier if you structure it like this:

<div class="loop-de-cores">Seu texto aqui<div>

You can configure the element using data attributes:

<div class="loop-de-cores" data-tempo="300">Olá Mundo!<div>

Make jQuery create the elements for you and then animate them. The example below already supports setting using the data attributes, so you can have more than one loop on the same page using different text, colors, and speeds.

// Para cada loop que você tiver na página, executar essa função:
$('.loop-de-cores').each(function () {
  // Guarda o elemento em uma variável:
  var $this = $(this);

  // Guarda algumas configurações e seus valores padrão:
  // Você pode alterá-las usando "data-[nome da configuração]='valor da configuração'" no HTML:
  var tempo = $this.data('tempo') || 100;
  var cores = ($this.data('cores') || '#ff00ff,#ff00cc,#ff0099,#ff0066,#ff0033,' +
  '#ff0000,#ff3300,#ff6600,#ff9900,#ffcc00,#ffff00,#ccff00,#99ff00,#66ff00,' +
  '#33ff00,#00ff00,#00ff33,#00ff66').split(',');

  // Para melhorar a performance:
  var numeroCores = cores.length;

  // Cria os elementos:
  $this.html('<span>' + $this.text().split('').join('</span><span>') + '</span>');

  // Armazena-os em uma variável:
  var $span = $this.find('span');

  // Inicia o loop:
  setInterval(function () {
    // Rotaciona a array [ver nota]
    cores.unshift(cores.pop());

    // Aplica os estilos:
    $span.each(function (index) {
      // Usa a função '.css' para aplicar os estilos:
      $(this).css('color', cores[index%numeroCores]);
    });
  }, tempo);
});

JSBin Example

Note: For best performance use one of these functions: link

    
06.03.2014 / 15:20
3

What you need to do is to change the order of the array of colors with each round. Your code should look like this:

var deslocamento = 0;
setInterval(function()
{
    //Removi os vetores cores e letras para dar uma limpada no código mais eles ainda existem
    var coresUsaveis =[];
    for(var i = 0; i <  cores.length; i++){
      if(i+deslocamento < cores.length) coresUsaveis.push(cores[i+deslocamento]);
      else coresUsaveis.push(cores[i+deslocamento-cores.length]); //Caso seja maior que o tamanho de cores, volta do zero
        }
    if(++deslocamento == cores.length){ //Caso já tenha dado a "volta" no vetor
        deslocamento = 0;
    }
    for (var i = 0; i <= coresUsaveis.length; i++) 
    {
        $("font[class ="+letras[i]+"]").css('color', coresUsaveis[i]);
    }
},500);

Here is the complete modified example .

    
06.03.2014 / 15:18
3

Without changing the vector, you can create an auxiliary variable to tell the initial color of the vector where each loop will start. This variable is incremented once every time the timer is run.

It is also necessary to make a control of the limit, since starting from any initial position, we must go through the array as if it were a circular list.

See the implementation I made:

var cont = 0;
setInterval(function()
{
    var cores = 
    [
        "#ff00ff",
        "#ff00cc",
        "#ff0099",
        "#ff0066",
        "#ff0033",
        "#ff0000",
        "#ff3300",
        "#ff6600",
        "#ff9900",
        "#ffcc00",
        "#ffff00",
        "#ccff00",
        "#99ff00",
        "#66ff00",
        "#33ff00",
        "#00ff00",
        "#00ff33",
        "#00ff66"
    ]

    letras =
    [
        "a","b","c","d","e","f","g","h","i","j","l","m","n","o","p","q","r","s"
    ]
    var div = []
    for (var i = 0, di = cont; i < cores.length; i++, di--) 
    {
        if (di < 0) {
            di = cores.length - 1;
        }
        div.push(di)
        $("font[class ="+letras[i]+"]").css('color', cores[di]);
    }
    console.log(cont, div);
    cont++;
    if (cont >= cores.length) {
        cont = 0;
    }
},500);

Jsfiddle

    
06.03.2014 / 15:22
0

So try random colors

 setInterval(function()
    {
        var cores = 
        [
            "#ff00ff",
            "#ff00cc",
            "#ff0099",
            "#ff0066",
            "#ff0033",
            "#ff0000",
            "#ff3300",
            "#ff6600",
            "#ff9900",
            "#ffcc00",
            "#ffff00",
            "#ccff00",
            "#99ff00",
            "#66ff00",
            "#33ff00",
            "#00ff00",
            "#00ff33",
            "#00ff66"
        ]

        letras =
        [
            "a","b","c","d","e","f","g","h","i","j","l","m","n","o","p","q","r","s"
        ]

        for (var i = 0; i <= cores.length; i++) 
        {
            $("font[class ="+letras[i]+"]").css('color', cores[Math.floor(Math.random()*cores.length)]);
        }
    },500);

Example: link

    
06.03.2014 / 15:18