Javascript replacement of sentences

Asked

Viewed 126 times

-3

How could I replace sentences on a particular part of my site in time intervals using javascript.

  • Create a list of texts that you want to appear, define a function that displays one of these texts and make this function run from time to time with the setInterval. I believe that with this you can at least try to do something and leave from scratch;

2 answers

0

As suggested by Anderson Carlos Woss, utilize setInterval with a list of sentences to be presented. I made a code fragment to help you:

var frases = ["Frase 1",
              "Frase 2",
              "Frase 3",
              "Frase 4"];
var count = 0;

var changeText = function(){
  if(count <= 3){
    $("#txt").text(frases[count]);
    count++;
  }else{
    count = 0;
  }
};

$(document).ready(function(){
  setInterval(changeText, 1000);
}); 

0

Javascript-enabled

Following the guidance of Anderson Carlos Woss, there is nothing wrong, see comments in the code

var i = 0;
var frase = [];

// Crie uma lista de textos que você deseja que apareça
frase[0] = "Como poderia substituir frases";
frase[1] = "em uma determinada parte do meu site";
frase[2] = "em intervalos de tempo";
frase[3] = "usando javascript. ";
frase[4] = "Valeu Anderson Carlos Woss. ";

//defina uma função que exiba um desses textos
function rodarFrases() {
   
   document.getElementById("texto").innerHTML = frase[i++];

   if (i >= frase.length)
      i = 0;
      //e faça com que essa função seja executada de tempos em tempos

   setTimeout("rodarFrases()", 3000);  
}

rodarFrases();
<div id="texto"></div>

With Jquery

(function(){
    var words = [
        'Como poderia substituir frases',
        'em uma determinada parte do meu site',
        'em intervalos de tempo',
        'usando jquery.'
        ], i = 0;
    setInterval(function(){
        $('#texto').fadeOut(function(){
            $(this).html(words[i=(i+1)%words.length]).fadeIn();
        });
    }, 3000);
        
})();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
    <span id="texto">Como poderia substituir frases</span>
</div>

Browser other questions tagged

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