Reputation: 227
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.
Upvotes: 21
Views: 66081
Reputation: 305
setInterval(function(){
alert('hello, do you have a beer?');
}, 1000);
where 1000 ms = 1 second.
Upvotes: 3
Reputation: 8942
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>
Upvotes: 48
Reputation: 165951
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.
Upvotes: 3
Reputation: 1038720
You may take a look at the setInterval
method. For example:
window.setInterval(function() {
// this will execute on every 5 seconds
}, 5000);
Upvotes: 4