0

Basically I have this code that hooks onto a certain element in the website and overrides it's content. In this example it's overriding existing text to make it change every so often. However when it cycles through the preset text lines it simply jumps without an animation. Is it possible to add a fade animation between the preset texts?

Here is the code:

    var text = ["Question Everything!", "Envision the future!", "Change your perspective!"];
    var counter = 0;
    var elem = document.getElementById("slogantxt");
    setInterval(change, 3500);

    function change() {
      elem.innerHTML = text[counter];
      counter++;
    if(counter >= text.length) { counter = 0; }
   }
Prabhat Sinha
  • 1,500
  • 20
  • 32

3 Answers3

1

CSS3 @keyframes animations would be much lighter weight here.

@keyframes fadeOutIn {
  0% {opacity: 1;}
  50% {opacity: 0;}
  100% {opacity: 1;}
}

.fadeOutIn {
  animation-name: fadeOutIn;
  animation-duration: 200ms;
 }

And then simply remove and re-add the class when changing the inner HTML.

EDIT: for simplicity, I left out the necessary -webkit- prefixes. Don't forget!

0

With jQuery you could do something like this:

$(document).ready(function(){
  var text = ["Question Everything!", "Envision the future!", "Change your perspective!"];
  var counter = 0;
  setInterval(change, 3500);
  function change() {
     $("#slogantxt").fadeOut('fast',function(){//fade out the element
         $(this).html(text[counter]).fadeIn('fast');//once fade out completes, change the element text and fade it back in
     });

     counter++;
     if(counter >= text.length) { counter = 0; }
   }
});
Biruk Abebe
  • 2,235
  • 1
  • 13
  • 24
0

With JS you can do like below

var text = ["Question Everything!", "Envision the future!", "Change your perspective!"];
var counter = 0;
var elem = document.getElementById("slogantxt");
setInterval(change, 3500);
function change() {
 fade(elem,function(){
    elem.innerHTML = text[counter];
    unfade(elem);
 }); 
 counter++;
 if(counter >= text.length) { counter = 0; }
}


function fade(element,cbk) {
   var op = 1;  // initial opacity
   var timer = setInterval(function () {
       if (op <= 0.1){
           clearInterval(timer);
           element.style.display = 'none';
           cbk();
       }
       element.style.opacity = op;
       element.style.filter = 'alpha(opacity=' + op * 100 + ")";
       op -= op * 0.1;
   }, 50);
}

function unfade(element) {
   var op = 0.1;  // initial opacity
   element.style.display = 'block';
    var timer = setInterval(function () {
       if (op >= 1){
           clearInterval(timer);
       }
       element.style.opacity = op;
       element.style.filter = 'alpha(opacity=' + op * 100 + ")";
       op += op * 0.1;        
   }, 10);
}

Ref: How to do fade-in and fade-out with JavaScript and CSS

Community
  • 1
  • 1
Gowsikan
  • 5,571
  • 8
  • 33
  • 43