Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery replace text every 2 seconds with words from an array

I want to replace a text in a span with the id "words" with words from an array every 2 seconds

$('#words').delay(1000).fadeOut(1000);
    $(this).delay(3000).text('word2').fadeIn(1000);
$(this).delay(5000).text('word3').fadeIn(1000);
$(this).delay(7000).text('word4').fadeIn(1000);

This is what I've got but obviously it stops working after 7 seconds.. how can I repeat this? Or even use an array to hold the words.. Thank you!

like image 521
Marc Ster Avatar asked Sep 07 '15 20:09

Marc Ster


People also ask

Which method is used to replace with the keyword jQuery?

jQuery replaceWith() Method The replaceWith() method replaces selected elements with new content.

How do you replace an element with another in jQuery?

We can replace HTML elements using the jQuery . replaceWith() method. With the jQuery replaceWith() method, we can replace each element in the set of matched elements with the provided new content and return the set of elements that were removed.


2 Answers

You can use setInterval() to do this:

$(function () {
  count = 0;
  wordsArray = ["Beta", "Gamma", "Delta", "Alpha"];
  setInterval(function () {
    count++;
    $("#word").fadeOut(400, function () {
      $(this).text(wordsArray[count % wordsArray.length]).fadeIn(400);
    });
  }, 2000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="word">Alpha</div>
like image 55
Praveen Kumar Purushothaman Avatar answered Oct 22 '22 19:10

Praveen Kumar Purushothaman


This is easily achievable using just Vanilla JS (normal JS without jQuery) as shown below.

Create a setInterval() loop to run every 2 seconds and randomize each time to get a different array element.

var names = ['test1', 'test2', 'test3', 'test4'];

setInterval(function() {
  var rand = Math.floor(Math.random() * 4);
  document.getElementById("name").innerHTML = names[rand];
}, 2000);
<div id="name">test</div>

If you want to have a fading effect (as mentioned in a comment) your best option will be to use jQuery.

like image 34
Stewartside Avatar answered Oct 22 '22 19:10

Stewartside