Ahmet Ömer
Ahmet Ömer

Reputation: 644

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 want it change smoothly but not pop up suddenly.

// change text every 3 second
    var text = ["Hola", "Hallo", "Merhaba"];
    var counter = 0;
    var elem = document.getElementById("greeting");
    setInterval(change, 3000);
    function change() {
     elem.innerHTML = text[counter];
        counter++;
        if(counter >= text.length) { counter = 0; }
    }

Upvotes: 8

Views: 18416

Answers (3)

F3L1X79
F3L1X79

Reputation: 2665

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);
function change() {
    elem.fadeOut(function(){
        elem.html(text[counter]);
        counter++;
        if(counter >= text.length) { counter = 0; }
        elem.fadeIn();
    });
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='greeting'>Hello<div>

Upvotes: 9

Dr._Duck
Dr._Duck

Reputation: 135

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

var greet = new Array("Hola", "Hallo", "Merhaba");

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

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

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

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

Is that what you want

Upvotes: 4

emanek
emanek

Reputation: 421

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:

function change() {
   // 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);
   })
}

Upvotes: 1

Related Questions