JMay
JMay

Reputation: 361

CSS transition using javascript

I'm trying to get text to fade in by adding a class name("fade") through javascript and having the opacity set as 1. When the fade class is added, the opacity does change to 1 but there is no transition effect. I've read similar questions and the answers said you need a delay but I'm not understanding how to do this. Any help would be appreciated.

function showSlides(n) {
    let text = document.getElementsByClassName("text");
    console.log(text);
    slideIndex += n;
    console.log(slideIndex);
    let slides = document.getElementsByClassName("mySlides");
    if (slideIndex < 0) {
        slideIndex = slides.length - 1;
    }
    if (slideIndex > slides.length -1) {
        slideIndex = 0;
    }
    for (i=0; i < slides.length; i++) {
        slides[i].style.display = "none";
        text[i].classList.remove("fade");
    }

    slides[slideIndex].style.display = "block";
    text[slideIndex].className += " fade"; (text should ease in. Opacity from 0 to 1)
}

css

.text {
    position: absolute;
    top: 30%;
    right: 10%;
    text-align: right;
    color: white;
    opacity: 0;
    transition: opacity 5s ease;
}

.fade {
    opacity: 1;
}

Upvotes: 2

Views: 55

Answers (1)

Cheeroke
Cheeroke

Reputation: 118

Try animation

.fade {
animation: fadeIn ease .8s;
opacity: 1;
}

@keyframes fadeIn {
0%   { opacity: 0}
100% { opacity: 1}
}

Upvotes: 3

Related Questions