Is there a way to add the fade-in animation to an image when it is loaded with JavaScript or CSS? Currently, the code I have only fades in the image once it is 25% visible in the viewport. How can I modify it to include the fade effect upon image load?
let options = {
root: null,
rootMargin: '0px',
threshold: 0.25 // Visible by 25%
};
let callback = (entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting &&
entry.target.className === 'lazyImage') {
let imageUrl = entry.target.getAttribute('data-img');
if (imageUrl) {
entry.target.src = imageUrl;
observer.unobserve(entry.target);
}
}
});
}
let observer = new IntersectionObserver(callback, options)
observer.observe(document.querySelector('#lazyImageId'))
.lazyImage {
height: 100%;
width: 100%;
position: absolute;
top: 0px;
left: 0px;
object-fit: cover;
animation-duration: 1s;
animation-fill-mode: both;
animation-name: fadeIn;
}
@keyframes fadeIn {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<div class="col-md-6 col-sm-12 full-height">
<img id="lazyImageId" class="lazyImage" data-img="./img/dog.jpeg" alt="" loading="lazy">
</div>