Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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

functionchange() {
    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);

functionchange() {
    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;
}
<h2id="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.

Solution 2:

Replace this part:

elem.innerHTML = text[counter];

With:

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

Post a Comment for "How To Add Fade In And Fade Out When Changing Between Texts In Javascript"