6

I have a span, eg:

<p>Here is a sentence <span id="rotate">this</span> is what changes</p>

and I'd like the contents of that span to change every few moments between a list of terms, so the contents might change to be:

<span id="rotate">then</span>
<span id="rotate">thus</span>

and so on. I'd like the text to fade out and then the new text fade in.

Whats the best way to do this via jquery?

Peter Clark
  • 263
  • 1
  • 3
  • 6

1 Answers1

14

You could do something like this, storing the current index on the element rotating using .data() to support it multiple places as well:

var terms = ["term 1", "term 2", "term 3"]; //array of terms to rotate

function rotateTerm() {
  var ct = $("#rotate").data("term") || 0;
  $("#rotate").data("term", ct == terms.length -1 ? 0 : ct + 1).text(terms[ct])
              .fadeIn().delay(2000).fadeOut(200, rotateTerm);
}
​​​​​​​​​​​​​​​​​​​$(rotateTerm); //start it on document.ready
​

This fades the first term in, waits 2 seconds, fades it out, changes the text and repeats....just adjust the values to what you want :)

Here's a quick demo so you can see it in action

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • Great answer! This works. However, could you perhaps explain what's happening here? I'm curious what does the variable "ct" means? – DavidVII Feb 18 '14 at 00:35
  • 1
    @DavidBecerra it's just my shorthand for "current term" - it's not longer simply so the code cleanly fits here without scrolling. – Nick Craver Feb 18 '14 at 01:09
  • @NickCraver This is quite old, but I have a similar need, however it is a bit more complex. I need to rotate 2 different strings of text, one says "coming soon" in 4 different languages and the second string says "subscribe to be informed". I need these to fade-in/-out synchronised so that the languages match. I tried defining two vars for the two arrays, changing the id="rotate" to a class and then tried an if statement to load the appropriate var, but it doesn't work. Any ideas? Also, I actually used the concept here http://jsfiddle.net/kMBMp/ but modified for 2 strings – Ali Samii Nov 07 '14 at 18:35