1

Hello stackoverflow community,

my goal is to create changing text with different duration, meaning that there are certain "markers" or sentences which stay longer then the 2 seconds I have now as of now. Also, I would like the animation to stop after all the list entries have been displayed.

Here is the code I have for now:

http://jsfiddle.net/eu8L01nv/

Javacript:

    var terms = $("ul li");

    function rotateTerm() {

     var ct = $("#rotate").data("term") || 0;

     console.log(terms.eq([ct]).text());

      $("#rotate").data("term", 
        ct == terms.length -1 ? 0 : ct + 1).text(terms.eq([ct]).text())
      .fadeIn().delay(2000).fadeOut(200, rotateTerm);

    }
    $(rotateTerm);

HTML

    <p><span id="rotate">default</span></p>

    <ul style="display:none">
        <li>This is sentence number one.</li>
        <li>That is sentence number two.</li>
        <li>This is another sentence.</li>
        <li>Another sentence.</li>
    </ul>

Thank you!

1 Answer 1

1

I hope this solves the issue:

I added this piece of code to it: ct < terms.length -1 && rotateTerm. so that it won't call rotateTerm function after the last element

And I have added a timeDelay array var timeDelay = [1000, 2000, 4000, 8000] to enable different time delays for different sentences.

var terms = $("ul li");

    function rotateTerm() {

     var timeDelay = [1000, 2000, 4000, 8000];
     var ct = $("#rotate").data("term") || 0;
     console.log(terms.eq([ct]).text());
     console.log(ct)
      $("#rotate").data("term", 
        ct == terms.length -1 ? 0 : ct + 1).text(terms.eq([ct]).text())
      .fadeIn().delay(timeDelay[ct]).fadeOut(200, ct < terms.length -1 && rotateTerm);

    }
    $(rotateTerm);

Or you could set the delay depending upon the length of the text

var terms = $("ul li");

function rotateTerm() {

  var ct = $("#rotate").data("term") || 0;
  const text = terms.eq([ct]).text()
  const textLength = text.length;
  console.log(textLength)
  const timeDelay = textLength < 50 ? 2000 : textLength * 50
  $("#rotate").data("term",
      ct == terms.length - 1 ? 0 : ct + 1).text(text)
    .fadeIn().delay(timeDelay).fadeOut(200, ct < terms.length - 1 && rotateTerm);

}
$(rotateTerm);

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, that helps me already a lot! Do you also know if there is any way to display some sentences longer, maybe be creating some unique list elements?
yes. I have updated the answer as per your requirement. Hope it helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.