71GA 71GA - 1 month ago 5
CSS Question

Adding fade-in to javascript timer

In my html body I am using a javascript that writes and changes a line of text in my div, with ID "moto", every 5 seconds.



var text = ["TEXT 1","TEXT 2","TEXT 3","TEXT 4"];
var counter = 0;
var elem = document.getElementById("moto");
ChangeFunction();
setInterval(ChangeFunction, 5000);

function ChangeFunction() {
elem.innerHTML = text[counter];
counter++;
if(counter >= text.length) { counter = 0; }
}

#moto{
-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;
}

<div id="moto"></div>





Do I need to apply some java fade-in fade-out? I would rather use CSS...

Answer

You can use jquery to do this easily as below

var text = ["TEXT 1","TEXT 2","TEXT 3","TEXT 4"];
var counter = 0;
var elem = document.getElementById("moto");
ChangeFunction();
setInterval(ChangeFunction, 5000);

function ChangeFunction() {
    var moto = text[counter++];
    $(elem).fadeOut('slow', function() {
      $(elem).html(moto);
      $(elem).fadeIn('slow');
    });

    if(counter >= text.length) { counter = 0; }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="moto"></div>