JavaScript how to make a changing text

Learn how to use Javascript to dynamically change text with an example. Create dynamic text with ease!

Changing Text with JavaScript

Changing text with JavaScript is a great way to give any page more interactivity. It can be used to create dynamic text, replace one set of words with another, or even to create a slideshow of different text. Here is an example of how to create a changing text effect using JavaScript.

HTML Markup

The HTML markup for the example consists of a <div> element with a unique id, and a set of <span> elements each containing a single word.

<div id="changingText">
  <span>This</span>
  <span>is</span>
  <span>a</span>
  <span>changing</span>
  <span>text</span>
  <span>example</span>
</div>

JavaScript Code

The JavaScript code for this example is quite simple. We first get a reference to the <div> element, and then create an array of the <span> elements inside the <div>.

var changingText = document.getElementById('changingText');
var words = changingText.getElementsByTagName('span');

We then create a function to rotate the words in the array. This function will loop through the array, setting the style.display property of each element to either block or none, depending on the current position in the array.

function rotateWords() {
  for (var i=0; i < words.length; i++) {
    words[i].style.display = (i === currentWord) ? 'block' : 'none';
  }
  currentWord = (currentWord + 1) % words.length;
}

Finally, we need to create a way to call the rotateWords() function at regular intervals. We can do this by using the setInterval() function, which will call the function every few seconds.

setInterval(rotateWords, 2000);

That's it! Now the <div> will contain a different word every two seconds.

Answers (0)