Skip to content Skip to sidebar Skip to footer

I Want My Text Change Animation In Javascript To Have Smooth Transition

So I have an h1 ('Hello, I'm xxxxxxxxx') and wraped 'Hello' in span with 'greeting' id and I change the text in js every 3s to an Hello in another language. It works fine but I wan

Solution 1:

With Jquery, you might want to use fadeOut(), then fadeIn() functions. And your code would be like:

var text = ["Hola", "Hallo", "Merhaba"];
var counter = 0;
var elem = $("#greeting");
setInterval(change, 3000);
functionchange() {
    elem.fadeOut(function(){
        elem.html(text[counter]);
        counter++;
        if(counter >= text.length) { counter = 0; }
        elem.fadeIn();
    });
}
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divid='greeting'>Hello<div>

Solution 2:

You could do it just by adding some css and using the transition property.

var greet = newArray("Hola", "Hallo", "Merhaba");

var counter= 0;
document.getElementById('greeting').innerHTML = greet[counter];

Changegreeting1();
functionChangegreeting1(){
  incrementIndex()
  document.getElementById('greeting1').innerHTML = greet[counter];

  document.getElementById('greeting').style.opacity = 0;
 
  document.getElementById('greeting1').style.opacity = 1;

  setTimeout(Changegreeting, 2000);
}
functionChangegreeting(){
  incrementIndex();
  document.getElementById('greeting').innerHTML = greet[counter];
 
  document.getElementById('greeting').style.opacity = 1;
 
  document.getElementById('greeting1').style.opacity = 0;
 
  setTimeout(Changegreeting1, 2000);
}
functionincrementIndex(){
  if(counter < greet.length - 1 ){
    counter++;
  }else{
    counter = 0;
  }
}
#greeting{
    transition: opacity 1s;
}
#greeting1{
    transition: opacity 1s;
    position:absolute;
    top:0px;
    margin-top:0px
}
<pid = "greeting"></p><pid = "greeting1"></p>

Is that what you want

Solution 3:

If by "change smoothly" you mean some smooth transition, as in fade out and fade in, I would suggest looking at jQuery fadeOut and fadeIn methods.

The change() function with animation duration set to 100 could look something like this:

functionchange() {
   // Fade out
   $("#greeting").fadeOut(100, function() {
      // Increment the counter
      counter++;
      if(counter >= text.length) { counter = 0; }
      // Update the text and fade in
      $("#greeting").text(text[counter]).fadeIn(100);
   })
}

Post a Comment for "I Want My Text Change Animation In Javascript To Have Smooth Transition"