How to change between texts according to time?

Asked

Viewed 4,163 times

2

How do I alternate text with a set time on a div? I don’t know command in jQuery, I tried the code below but it doesn’t work.

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <div id="frases"></div>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
    <script>
      $(document).ready(function(){
        $('#frases').toggle
          function(){
            $('#frases').text("texto 1");
            $(this).show(5000);
          },
          function(){
            $('#frases').text("texto 2");
            $(this).show(5000);
          },
          function(){
            $('#frases').text("texto 3");
            $(this).show(5000);
          }
        });
      });
    </script>
  </body>
</html>

If anyone can help, thank you.

  • Why doesn’t it work? The text should repeat itself indefinitely?

2 answers

3


I have prepared an example with setInterval:

$(document).ready(function() {

    //textos a serem exibidos
    var textos = ["texto 1", "texto 2", "texto 3"];

    //exibição inicial
    var atual = 0;
    $('#frases').text(textos[atual++]);

    //define intervalo de troca
    setInterval(function() {

        //efeito de desaparecer
        $('#frases').fadeOut(function() {

            //função "callback" que mostra o próximo texto
            if (atual >= textos.length) atual = 0;
            $('#frases').text(textos[atual++]).fadeIn();

        });

    }, 3000);
});

Functional example in Jsfiddle

1

Can use setInterval, see an example below

HTML

<div class="texto"></div>

Jquery

$(function(){
var texto = 1;
var string;

setInterval(function(){
    switch(texto) {
        case 1: string = "Meu texto"; break;
        case 2: string = "Outro Texto"; break;
        case 3: string = "Mais um texto"; break;
    }

    $('.texto').html(string);

    texto != 3 ? texto++ : texto = 1;
}, 3000);
});

DEMO

Browser other questions tagged

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