1

when first time the button clicked, the fade animation(opacity changing) works. But for next all clicks it does'nt work anymore. When i do debug it shows it's working everytime. But in real why doesn't?

let colorArray = ['red','yellow','green','teal']
let index = 0

function imageChanger(){
    document.querySelector('.container').id = ''
    if(index == colorArray.length-1) index = 0
    else index++
    document.querySelector('.container').style.backgroundColor = colorArray[index]
    document.querySelector('.container').id = 'fade'
}
.container{
    height: 300px;
    max-width: 400px;
    background-color:  teal;
    
}
#fade{
    animation: fade 5s;
}
@keyframes fade{
    from{opacity:.4 }
    to{opacity: 1}
}
<button onclick="imageChanger()">Change</button>
<div class="container" id=""></div>

2 Answers 2

1

Once you added the fade id its run the animation and not repeat anymore.

You should remove it each time and add again. using setTimeout to give the css the time to find it removed.

Also I will reccomend to use class instead an id, and use transition instead keyframe

let colorArray = ['red','yellow','green','teal']
let index = 0

function imageChanger(){
    document.querySelector('.container').id = ''
    if(index == colorArray.length-1) index = 0
    else index++
    document.querySelector('.container').style.backgroundColor = colorArray[index]
    document.querySelector('.container').classList.remove('fade')
    setTimeout( function(){    document.querySelector('.container').classList.add('fade')
}, 50);
}
.container{
    height: 300px;
    max-width: 400px;
    background-color:  teal;
    opacity: .2;
    transition: opacity 0s linear;
}
.container.fade{
    transition: opacity 3s linear;
    opacity: 1;
}
<button onclick="imageChanger()">Change</button>
<div class="container fade"></div>

Sign up to request clarification or add additional context in comments.

Comments

0

I would mostly agree with the above answer. Just want to point out that if you want the first teal block to show up as teal and not opaque to start with, you need to include the fade class in your initial html.

Also if you want the first transition to be teal to red, you should start with an index position of -1 and not 0.

<button onclick="imageChanger()">Change</button>
<div class="container fade" id=""></div>

let index = -1;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.