0

I'm learning jQuery and JS. I have text in:

<p><em>"My text 1"</em></p>

How can I implement simple text slider (maybe array with texts and it will be change after 5s)? What function can I use? I need in array:

"My text 1"
"My text text"
"My text my text"
"My text other"

3 Answers 3

2
var myTexts = new Array("My text 1", 
                        "My text text", 
                        "My text my text", 
                        "My text other");
var currentText = 0;

var timeout = setInterval(nextText, 5000);

function nextText() {
    if (currentText >= myTexts.length) {
        currentText = 0;
    } else {
        currentText++;
    }

    $('em').html(myTexts[currentText]);
}

Basically what the code above does is:

  1. set your text within an array
  2. set an interval to call nextText() every 5 seconds
  3. in the function check which text to show (based on the length of your array)
  4. change the text within your 'em' element with jquery's html()-method.

-edit: typos...

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

Comments

0

Settimeout function. For example:

$(document).ready(function(){
      setTimeout(function(){
        $('#yourDivId').html('<p><em>Another text</em></p>');
      }, 2000);

})

This will change text in your div after 2 sec.

Comments

0

You can use:

var terms = ["My text 1", "My text text", "My text my text", "My text other"];

function rotateTerm() {
    var ct = $("#rotate").data("term") || 0;
    $("#rotate").data("term", ct == terms.length -1 ? 0 : ct + 1)
                .text(terms[ct])
                .fadeIn().delay(5000).fadeOut(200, rotateTerm);
};
rotateTerm(); 

Fiddle Demo

2 Comments

@user3284589 Right. $(function(){ is shorter.
@user3284589 Yes, you need to do so.

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.