user3882752
user3882752

Reputation: 273

How to add fade in and fade out when changing between texts in javascript

I have below my JAVASCRIPT code which change between 2 words every 2.5 seconds and I want to add fading to the transition between the words in the array it uses. I know that I need to use Jquery but how do I implement it in this recursive function? Any ideas?

var text = ["first", "second"];
var counter = 0;
var elem = document.getElementById("changeText");
setInterval(change, 2500);

function change() {
  elem.innerHTML = text[counter];
  counter++;
  if (counter >= text.length) {
    counter = 0;
  }
}
.banner-right h2 {
  font-size: 50px;
  font-weight: 300;
  color: #ffffff;
  margin: 15px 0 45px 0;
}
<h2 id="changeText">Data Scientist</h2>

Upvotes: 2

Views: 5822

Answers (2)

Sergio
Sergio

Reputation: 28837

Since you are using Native JavaScript you could use CSS transitions and classList.

Something like:

CSS

#changeText {
    opacity: 1;
    transition: opacity 0.5s;
}
.hide {
    opacity: 0 !important;
}

JavaScript

function change() {
    elem.classList.add('hide');
    setTimeout(function () {
        elem.innerHTML = text[counter];
        elem.classList.remove('hide');
        counter++;
        if (counter >= text.length) {
            counter = 0;
        }
    }, 500);
}

Demo:

var text = ["first", "second"];
var counter = 0;
var elem = document.getElementById("changeText");
setInterval(change, 2500);

function change() {
    elem.classList.add('hide');
    setTimeout(function () {
        elem.innerHTML = text[counter];
        elem.classList.remove('hide');
        counter++;
        if (counter >= text.length) {
            counter = 0;
        }
    }, 500);
}
#changeText {
    opacity: 1;
    transition: opacity 0.5s;
}
.hide {
    opacity: 0 !important;
}
<h2 id="changeText">Data Scientist</h2>

Note: I used !important in the CSS because opacity: 1; when applied with a ID selector has priority over a class selector.

Upvotes: 5

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167172

Replace this part:

elem.innerHTML = text[counter];

With:

$(elem)
    .fadeOut(400)
    .html(text[counter])
    .delay(400)
    .fadeIn(400);

Upvotes: 1

Related Questions