Home > Enterprise >  Add transition to changin text in javascript
Add transition to changin text in javascript

Time:10-11

I have the below code to change the text on interval. I want to add a transition for opacity while changing the text. There are other answers which use fade in and out method of jquery but did not work with the given javascript code.

var text = ["Welcome", "Hi", "Sup dude"];
var counter = 0;
var elem = document.getElementById("changeText");
var inst = setInterval(change, 1000);

function change() {
  elem.innerHTML = text[counter];
  counter  ;
  if (counter >= text.length) {
    counter = 0;
    // clearInterval(inst); // uncomment this if you want to stop refreshing after one cycle
  }
}
<div id="changeText"></div>

Updated code

function change() {
      elem.innerHTML = text[counter];
      document.getElementById('s2main').style.opacity = 1;
      counter  ;
      if (counter >= text.length) {
        counter = 0;
        // clearInterval(inst); // uncomment this if you want to stop refreshing after one cycle
      }
    }

added CSS

#changetext{
opacity:0;
transition: opacity 400ms

the transition only works for the first text and also transition takes 3s.

CodePudding user response:

The easiest way is to use css transitions:

#changeText {
    transition: opacity 400ms;
}

You can then set the opacity value with JS, or even remove/ add different classes to speed up or remove the effect.

Since you tagged jQuery but dont seem to use any, jQuery has inbuilt fade animations:

$('#changeText').finish().fadeTo(300, 0, function() {
    // do stuff
    // fade back in again
    $('#changeText').finish().fadeTo(300, 1);
});

CodePudding user response:

You can use another element as a container and change the container's opacity. If you want to make one text fade into the next one, instead of fading out and in, then you could use more than 1 span elements here.

Also note, this is a rough code, not yet visually elegant, so you should tune the timings to your needs.

var text = ["Welcome", "Hi", "Sup dude"];

var counter = 0;
var elem = document.getElementById("changeText");
var elemContainer = document.getElementById("changeTextContainer");
var inst = setInterval(change, 1000);

function showText() {
    elemContainer.style.opacity = 1;
}
function change() {
    elemContainer.style.opacity = 0;
    elem.innerHTML = text[counter];
    setTimeout (showText, 500);
    counter  ;
    if (counter >= text.length) {
        counter = 0;
    }
}
#changeTextContainer {
    transition: opacity 400ms;
}
<div id="changeTextContainer"><span id="changeText"></span></div>

  • Related