Help adding fade in and out

I am trying to add fade in and out to my javascript code. Can someone please help me.

<script>
var text = ["Welcome", "Hi", "Sup dude"];
var counter = 0;
var elem = document.getElementById("changetext");
var inst = setInterval(change, 2500);

function change() {
  elem.innerHTML = text[counter];
  counter++;
  if (counter >= text.length) {
    counter = 0;
    // clearInterval(inst); // uncomment this if you want to stop refreshing after one cycle
  }
}
</script>

Sure. If you don’t mind using jQuery, this’ll do you:

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Text fade in/out</title>
  </head>

  <body>
    <div id="changetext">Welcome</div>

    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script>
      var text = ["Welcome", "Hi", "Sup dude"];
      var counter = 0;
      var elem = $("#changetext");
      var inst = setInterval(change, 2500);

      function change() {
        $(elem).fadeOut(
          1000,
          function(){
            elem.innerHTML = text[counter];
            $(elem).fadeIn();
          }
        );

        counter++;
        if (counter >= text.length) counter = 0;
      }
    </script>
  </body>
</html>

jQuery comes with quite a nice fadeIn/fadeOut function, which (among other things) allows you to set a duration for the fade effect, as well as a callback to be run once the transition has taken place.

Ref:
https://api.jquery.com/fadeIn/
https://api.jquery.com/fadeOut/

Edit: If you’d rather do this without any external libraries, you might like to read this: http://www.chrisbuttery.com/articles/fade-in-fade-out-with-javascript/

Do you have to use JavaScript? You can just use JavaScript to apply/remove these classes.

.fadeIn {
  animation: fadein 2500ms;
}

.fadeOut {
   animation: fadeout 2500ms;
}

@keyframes fadein {
  from: { opacity: 0; }
  to: { opacity: 1; }
}

@keyframes fadeout {
  from : { opacity: 1; }
  to: { opacity: 0; }
}

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.