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!
jQuery replaceWith() Method The replaceWith() method replaces selected elements with new content.
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.
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>
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With