Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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; }
    }
like image 878
Ahmet Ömer Avatar asked Jun 27 '17 13:06

Ahmet Ömer


2 Answers

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>
like image 68
F3L1X79 Avatar answered Oct 10 '22 16:10

F3L1X79


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

like image 28
Dr._Duck Avatar answered Oct 10 '22 16:10

Dr._Duck