How to change text with document.write and delete past text

Viewed 46

I want to make a loading animation for a website, and I thought that these Unicode characters would look good:☰ ☱ ☲ ☴ but I don't know how to do this.

2 Answers

There are a number of methods for setting the content of an element. It's just a case of using either setTimeout or setInterval to keep changing the content after a pause.

For example:

const chars = ['☰','☱', '☲', '☴'];
const el = document.getElementById('spinner');

let index = 0;

function changeChar() {
  el.innerText = chars[index];
  index = (index + 1) % chars.length;
  setTimeout(changeChar, 200);
}

changeChar()
<div id="spinner" />

You can do it with something like this:

var animationContainer = document.querySelector('#animation');
var animationThing = 0;

setInterval(function() {
  switch (animationThing) {
    case 0:
        animationContainer.innerHTML = '☰';
        animationThing++;
        break;
        
    case 1:
        animationContainer.innerHTML = '☱';
        animationThing++;
        break;
        
    case 2:
        animationContainer.innerHTML = '☲';
        animationThing++;
        break;
        
    case 3:
        animationContainer.innerHTML = '☴';
        animationThing = 0;
        break;
   }
}, 200);
<span id="animation"></span>

Related