changing text with different duration in javascript

148 Views Asked by At

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

There are 1 best solutions below

2
thealpha93 On BEST ANSWER

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);