Issue
I have a site where I want to have images that change from black and white to colour when the viewer scrolls. The images are originally in color but I used a css filter to create the grayscale effect.
How can I achieve this effect on the scroll? I know how to create the effect when the viewer hovers over the image but I want to make it so that it changes on scroll.
Here is my code for the hover effect:
.contact {
filter: grayscale(100%);
-webkit-filter:grayscale(100%);
}
.contact:hover {
filter: grayscale(0);
-webkit-filter:grayscale(0);
}
Thank you for your help!
Solution
Define a class for black & white and another for color :
.contact {
filter: grayscale(100%);
-webkit-filter:grayscale(100%);*
}
.contact:hover, .contact-color {
filter: grayscale(0);
-webkit-filter:grayscale(0);
}
Then add a listener on window :
var images = document.getElementsByClassName('contact');
var changeFrom = 500; // from which amount of scroll do you want the effect to appear ?
window.addEventListener('scroll', function() {
if (window.scrollY >= changeFrom ) {
[].forEach.call(images, function(image) {
image.classList.add('contact-color');
});
}
else {
[].forEach.call(images, function(image) {
image.classList.remove('contact-color');
});
}
});
Color will will change when the the defined amount of vertical scrolling is reached and will revert if you scroll up. I don't know if it's exactly what you want but you may easily adapt it depending on your needs.
Answered By - Joulss
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.