0

I am trying to use animate to make images transition from zero opacity to full opacity. The keyframes animation code i have used works but i want to delay the start until the image is in view. I have tried several JS codes which have not worked.

HTML

<div class="item2">
 <img src="images/winston-chen-qg8TGmBNdeY-unsplash.jpg" width="950" height="700" alt="wintson cheng unsplash" class="img">                     
</div>

CSS

@keyframes animate {
 from {opacity: 0;}
 to {opacity: 1;}
}

.img {
 width: 100vw;
 height: auto;
 animation-name: animate;
 animation-duration: 10s;
 animation-timing-function: ease-in;
}

QuickSilver
  • 3,915
  • 2
  • 13
  • 29
  • Does this answer your question? [Animating elements when they are in the viewport](https://stackoverflow.com/questions/34270530/animating-elements-when-they-are-in-the-viewport) – YourManDan Aug 16 '23 at 20:56

1 Answers1

0

You could do it easily with jQuery.

CSS:

img { opacity: 0; } /* this sets the opacity before it comes in so there isn't a jump */

.img {
     width: 100vw;
     height: auto;
}

.fadein {
     animation: animate 10s forwards;
}

jQuery:

https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js

Then in scripts file:

    $(function() {
      $(window).scroll(function() {
        var $img = $(".img");
        $img.each(function() {
            var $y = $(document).scrollTop(),
            $wh = $(window).height(),
            $t = $(this).offset().top - $wh;
            if ($y > $t) {
                $(this).addClass("fadein");
            }
        });
    });
});

Every time the .img tag comes into view it adds the fadein class and fades in.

Thomas James
  • 687
  • 2
  • 6
  • 21
  • Thank you, Thomas, I appreciate your help. I have managed to set all the images to 0 opacity, but the fadein animation is not working. Was I supposed to make adjustments to my HTML? Do I need to keep any of the keyframes code? I have tried to adjust the CSS and HTML code a bit but nothing seems to be working. – Regs McVeigh May 15 '20 at 13:04
  • Sorry I added a . in the addClass by mistake: I have created a pen for you to see - https://codepen.io/urbanedgedesign/pen/bGVQPpX – Thomas James May 19 '20 at 11:38
  • At the moment the code adds the class the moment it comes into view so the animation happens straight away. You can add a minus to delay it slightly so it is 50px into view before it shows: $wh = $(window).height() - 50, – Thomas James May 19 '20 at 11:41