21

I need JavaScript or jQuery something to change text every few seconds... without the user doing anything.

Example:

"Welcome" changes to "Salmat datang" changes to "Namaste", etc. after 3 seconds and loops back.

2
  • 1
    +1 @ Keoki. This is pretty simple Javascript, and surely the answer exists in many places all over the internet. Here's a hint: a function will need to call itself.
    – maxedison
    Commented Jun 18, 2011 at 20:02
  • 4
    @maxedison, you are providing a bad hint. It is not necessary to be a function that is calling itself. Commented Jun 18, 2011 at 20:07

4 Answers 4

48

As others have said, setInterval is your friend:

var text = ["Welcome", "Hi", "Sup dude"];
var counter = 0;
var elem = document.getElementById("changeText");
var inst = setInterval(change, 1000);

function change() {
  elem.innerHTML = text[counter];
  counter++;
  if (counter >= text.length) {
    counter = 0;
    // clearInterval(inst); // uncomment this if you want to stop refreshing after one cycle
  }
}
<div id="changeText"></div>

1
  • Is there any way to add fade in and out transition while changing text?
    – tru_shar
    Commented Oct 11, 2021 at 7:37
4

You may take a look at the setInterval method. For example:

window.setInterval(function() {
    // this will execute on every 5 seconds
}, 5000);
3

You can use setInterval to call a function repeatedly. In the function you can change the required text.

The list of texts to change between could be stored in an array, and each time the function is called you can update a variable to contain the current index being used. The value can loop round to 0 when it reaches the end of the array.

See this fiddle for an example.

3
setInterval(function(){
   alert('hello, do you have a beer?');
}, 1000);

where 1000 ms = 1 second.

Not the answer you're looking for? Browse other questions tagged or ask your own question.