"Forward/backward loop" - problem

Joined
Feb 19, 2025
Messages
2
Reaction score
0
Hello folks,

I`m rather new to coding.
I have a simple code.
Two pictures. The first picture has an opacity of 1 at the beginning the second has one of 0.
After a button click, both pictures which are overlapped start to change their opacity gradually. One becomes visible and the other invisible so to speak.
The first loop works fine. The opacity of the first picture gradually becomes smaller and the opacity of the second picture slowly increases.
My idea is to reverse the process after the first picture became "invisible" and the second "visible".
With my code the the pictures start to "blink fast" after the first process is completed. I already asked different AIs for advice, but non could help to solve the problem properly.
Thanks for any advice.

Code:

<script>
// document.getElementById("idAnimieren").addEventListener("click", function () { verweis = setInterval(animieren, 20); }); //

...
let verweis, wert = 1;
function animieren()
{

if (wert > 0) {
wert -= 0.01;
paradies.style.opacity = wert;
sofi.style.opacity = 1 - wert;
} else {
wert += 0.01;
paradies.style.opacity = 1 - wert;
sofi.style.opacity = wert;
}
}

</script>
...
 
Joined
Sep 21, 2022
Messages
229
Reaction score
38
You need a direction variable.
Code:
if (d == 1) {
 wert += 0.01;
} else {
 wert -= 0.01;
}
if (wert <= 0) {
 wert = 0;
 d = 1;
}
if (1 <= wert) {
 wert = 1;
 d = -1;
}
paradies.style.opacity = wert;
sofi.style.opacity = 1 - wert;
 
Joined
Feb 19, 2025
Messages
2
Reaction score
0
You need a direction variable.
Code:
if (d == 1) {
 wert += 0.01;
} else {
 wert -= 0.01;
}
if (wert <= 0) {
 wert = 0;
 d = 1;
}
if (1 <= wert) {
 wert = 1;
 d = -1;
}
paradies.style.opacity = wert;
sofi.style.opacity = 1 - wert;
It works. Thank you.
But to be honest I don't understand why your solution is working and mine isn't. I don't have a direction variable but the direction is stated anyway...

Probably because wert is not defined properly each time.
 
Last edited:
Joined
Sep 21, 2022
Messages
229
Reaction score
38
In your logic, wert does not go from 1 to 0 to 1, it gets stuck close to 0.

When wert is <= 0, 0.01 is added, which makes it > 0 again, which then causes your logic to subtract 0.01 again.

There's your "blink fast".
Code:
0.03
0.02
0.01
0     
0.01
0
0.01
0
...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,263
Messages
2,571,314
Members
47,945
Latest member
BlytheHoth

Latest Threads

Top