1

So, i am trying to do an animation on my image in html/css. The problem is, it triggers when i load the page, but i want it to trigger when i scroll down to the image.

Here is my HTML part:

<figure>
   <img src="Assets/Images/klenet.jpg" id="clenet_picture">  
   <figcaption id="clenet_text">Clenet Series 1 от 1979 година.</figcaption>
</figure>

Here is the CSS part:

#clenet_picture
{
   . . .

   animation-name: image-anim;
   animation-duration: 4s;
}
@keyframes image-anim
{
   from {opacity: 0%}
   to {opacity: 100%}
}

I know i need to use some JS to make it work, but how exactly do i do that?

pietrodito
  • 1,288
  • 9
  • 19

3 Answers3

1

Add another class to it using JS. For example animate

Then you can use #clenet_picture.animate instead of #clenet_picture and animation will only start when you have applied new class

How to check if image is in viewport: How can I tell if a DOM element is visible in the current viewport?

NoOorZ24
  • 1,825
  • 1
  • 9
  • 28
0

I think i found a very simple solution.

However, there is one stupid problem.

Here is the code:

const checkpoint = 750;

        window.addEventListener("scroll", () => {
            
            const currentScroll = window.pageYOffset;
            
            if (currentScroll <= checkpoint) {
                opacity = 1 - currentScroll / checkpoint;
            } else {
                opacity = 0;
            }
            
            document.querySelector(".toAnimate").style.opacity = opacity;
        });

The problem is that now it is doing the opposite... When i scroll to the picture, its opacity becomes 0 and when i scroll outside it, it becomes 1...

If someone has a solution, i will be thankful.

And thanks to all answers!

0

I fixed it!

Here is the working code:

//The checkpoint is set by you!
const checkpoint = 550;

        window.addEventListener("scroll", () => {
            
            const currentScroll = window.pageYOffset;
            
            if (currentScroll <= checkpoint) {
                opacity = 0 + currentScroll / checkpoint;
            } else {
                opacity = 1;
            }
            
            document.querySelector(".toAnimate").style.opacity = opacity;
        });

This is the most simple solution, works without CSS!