Reputation: 5791
I have text inside a DIV tag. Is it possible to change the text content with five different text contents in cycle that never ends? Sounds simple, but I'm trying to find the easiest approach with jquery or related.
Many thanks, Erik
Upvotes: 1
Views: 3301
Reputation: 359786
Really simple approach: use setInterval()
.
var text = ['foo', 'bar', 'baz'];
i = 0,
$div = $('#myDiv');
setInterval(function ()
{
$div.text(text[i++ % text.length]);
}, 1000);
http://jsfiddle.net/mattball/TJv3K/
Edit If you want to get fancier with the effects: http://jsfiddle.net/mattball/TJv3K/1/
Edit 2 re OP comments (below)
<script>
tags.Other fixes needed (shown in both fiddles):
Actually load jQuery from somewhere, otherwise none of this code will work.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
Remove the trailing comma at the end of the first text
array literal
text
array declarations to commas, otherwise the following variables (i
and $div
) will be declared as global, which is a bad thing.Upvotes: 4
Reputation: 38503
Hard to say your intentions, but you can use setInterval
to trigger a timer to append/change info in the div
.
<div id="change">initial content</div>
<script>
$(function() {
setInterval(update, 1000);
});
function update() {
$("#change").append(".");
}
</script>
Upvotes: 1
Reputation: 298156
Here's an example: http://jsfiddle.net/jbkjE/11/. It's a bit bigger than this because I added some elements to display the clockwork that's happening.
Here's the code:
var strings = ['Foo', 'Bar', 'FooBar', 'BarFoo', 'FooBarFoo'];
var index = 0;
function cycle()
{
$('#cycle').text(strings[index % strings.length]);
index++;
setTimeout(cycle, 500);
}
cycle();
You just cycle through the values of the array, and to do that, you modulo the length of the array (Google "modulo operator").
And a (kinda) one-liner:
var index = 0;
var strings = ['Foo', 'Bar', 'FooBar', 'BarFoo', 'FooBarFoo'];
$(function() { setInterval(function() {$('#cycle').text(strings[index++ % strings.length]);}, 1000); });
Upvotes: 0