Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am trying to create a simple jquery text rotator: I have a span in which text should fade in and out. There are similar questions here on stackoverflow but I can't apply their solutions to my situation Here is what I wrote so far and I was wondering why this code doesn't work:

var i=0;
function rotate(spanid,w1,w2,w3){
  var myspan = "#"+spanid;
  var words = [w1,w2,w3];
  $(words[i]).appendTo(myspan).fadeIn(2000).delay(2000).fadeOut(2000);
  i==words.length? i=0:i++;
  rotate(spanid,w1,w2,w3);    
  }

Is the approach to the problem correct? Why isn't this code working? Thank you all in advance!

EDIT The code isn't working as nothing is showing up. Here is the html section relative to the function:

<p>Blah blah blah <span id="rotate"></span> blah blah blah </p>
<script>
$(rotate("rotate","word1","word2","word3"));
</script>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
196 views
Welcome To Ask or Share your Answers For Others

1 Answer

Okay, i've had a quick play and expanded it a little for you..

JS Fiddle: http://jsfiddle.net/4k3zfv5f/

    function rotate(sID,aWords, iIndex){
        $("#"+sID).html(aWords[iIndex]).fadeIn(1000, function() {   
            iIndex==(aWords.length-1)? iIndex=0:iIndex++;           
            $("#"+sID).fadeOut(1000, function() {                   
                rotate(sID,aWords,iIndex);                          
            }); 
        });
    }



    rotate("test1",["Hello", "World", "Foo"], 0);
    rotate("test3",["John", "Bob", "Billy", "Mike", "Larry"], 0);

EDIT - UPDATE

Basically there were a few corrections i had to make, so instead of going over each one.. Will just let you compare the changes.. Part of it is that the fade functions did not wait til they completed, the Delay command only applies to the jquery object and the append i reversed just for my visual sake.

Also the last part as you mentioned in the comments, was to swap appendTo with html.

Just as an extra bonus, a shuffle example:

JS Fiddle Showing With Shuffle Example: http://jsfiddle.net/ye3rjy2v/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...