Color loop in text

Asked

Viewed 1,193 times

10

I have the following HTML structure:

<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 color previous to the one received in the previous loop?

Code

4 answers

9


You don’t have to use <font>, that is obsolete. Prefer to use tags <span>. But you also don’t need to use so many classes and elements, it’s easier if you structure like this:

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

You can configure the element using attributes data:

<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 configuration through attributes data, soon 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);
});

Example in Jsbin

Note: for better performance use one of these functions: https://stackoverflow.com/q/1985260/1850091

3

What you need to do is change the order of array color 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 the complete modified example.

3

Without changing the vector, it is possible to create an auxiliary variable to inform the initial color of the vector where each loop will start. This variable is incremented once each execution of timer.

It is also necessary to make a limit control, because 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

0

try so with the colors Random

 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: http://jsfiddle.net/UzUK2/

  • 1

    He does not want a random color, but a later letter color, in the previous.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.