Kittichote Chain
Kittichote Chain

Reputation: 681

How to change text animation using setInterval and styling by CSS?

I'm making a portfolio website. I want the background to be text automatically changing like 'HTML' to 'CSS' to 'JavaScript'. However, I also want them to change, not plainly, but in animation like zoomIn and zoomOut in animation.css. In other words, when the text 'HTML' disappear before changing to CSS, it gets smalller until you can't see and appear again bigger and bigger to 'CSS'. Sorry for the complication.

Currently, I have text changing overtime by implementing setInterval over array of words.

index.html

<h1 id="change"></h1>

main.js

const symbols = ['HTML', 'CSS', 'JavaScript']
count = 0
let inthandle = setInterval(() => {
  document.getElementById("change").innerHTML = symbols[count];
  count = (count + 1) % symbols.length
}, 2000)

Upvotes: 0

Views: 2135

Answers (2)

remix23
remix23

Reputation: 2994

You can achieve this zoom out transition by changing twice the scale transform for each element in symbols.

Note that the transition time must be half the setInterval period.

count needs to be inscremented by 2 to change the text, but the .out class id added then removed in alternance for each step.

The time interval has been divided by two to keep the same rate as before.

The h1 element also have to keep fixed size and text centered to give the illusion that it is the same text changing.

Finally the iteration callback is forced called once to immediately start the animation.

const symbols = ['HTML', 'CSS', 'JavaScript'];
let count = 0;
const element = document.getElementById("change");
const iteration = () => {
  element.innerHTML = symbols[parseInt(count / 2, 10) % symbols.length];
  if (count % 2 !== 0) {
    element.classList.add("out");
  } else {
    element.classList.remove("out");
  }
  count++;
  // if you're affraid the code could run for so long that it could fail,
  // 6 is enough (number of elems * 2)
  if (count === symbols.length * 2) {
      count = 0;
  }
};
let inthandle = setInterval(iteration, 1000);
iteration();
#change {
transition: transform 0.5s;
display: inline-block;
width: 200px;
text-align: center;
}


.out {
  transform: scale(0);
}
<h1 id="change">HTML</h1>

Upvotes: 3

G-Cyrillus
G-Cyrillus

Reputation: 105893

You could also add an a CSS animation 3 times longer than your interval.

const symbols = ['HTML', 'CSS', 'JavaScript']
count = 0
let inthandle = setInterval(() => {
  document.getElementById("change").innerHTML = symbols[count];
  count = (count + 1) % symbols.length
}, 2000)
#change {
  text-align: center;
  animation: 6s colors infinite;
}

@keyframes colors {
  16.66%,
  50%,
  56%,
  83.31% {
    color: tomato;
    font-size: 3rem;
  }
  0%,
  33.33%,
  66.65%,
  100% {
    color: lightblue;
    font-size: 2rem;
  }
}
<h1 id="change"></h1>

Inside animation, you can use transform to avoid content jumping

Upvotes: 1

Related Questions