Reputation: 1
As mentioned in the title I am trying to change a background-image on scroll and adding a nice transition with ease.
The background-image should be fixed and stays in position. The content is moving.
Any ideas?
I managed to get the image changed but the transition is not working.
<script>
document.addEventListener('DOMContentLoaded', function () {
var backgroundContainer = document.querySelector('.background-container');
// Add more images if you like.
var backgroundImages = ['image1.jpg', 'image2.jpg'];
var currentImageIndex = 0;
// Set first background image
backgroundContainer.classList.add('background-image-1');
window.addEventListener('scroll', function () {
// Check if you have scrolled to the top.
var scrolledToTop = window.scrollY === 0;
// Change backgroundclass
if (scrolledToTop) {
currentImageIndex = 0;
backgroundContainer.classList.remove('background-image-2');
backgroundContainer.classList.add('background-image-1');
} else {
currentImageIndex = 1;
backgroundContainer.classList.remove('background-image-1');
backgroundContainer.classList.add('background-image-2');
}
backgroundContainer.style.transition = 'background-image 1.5s ease';
});
});
</script>
Upvotes: 0
Views: 65
Reputation: 14407
Yes, only CSS properties which take decimal values are animatable. So opacity
is animatable, but background-image
is not.
Simplest solution is probably to stack several images and animate their opacity.
Upvotes: 0