Erik
Erik

Reputation: 5791

How can alter text in a loop in a DIV

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

Answers (3)

Matt Ball
Matt Ball

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)

  • Fix #1: use distinct variable names for each rotator, because variable scoping is unaffected by <script> tags.
  • Fix #2: don't change variable names, but use closures so that the global scope isn't polluted.

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

  • Change the semicolons following the two text array declarations to commas, otherwise the following variables (i and $div) will be declared as global, which is a bad thing.

Upvotes: 4

Dustin Laine
Dustin Laine

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>

Working example

Upvotes: 1

Blender
Blender

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

Related Questions