I'm trying to cycle through some images and remove a filter from them one at a time.
var h = 0;
function removeGreyscale() {
document.images[h].style.webkitfilter = "grayscale(0)";
document.images[h].style.filter = "grayscale(0)";
h += 1;
if (h === 8) {
h = 0;
}
}
setInterval(removeGreyscale, 3000);
This code is currently not working.
It looks like you need to capitalize the 'f' in the webkitFilter
property:
document.images[h].style.webkitFilter = "grayscale(1)";
document.images[h].style.filter = "grayscale(1)";
Chrome still requires the -webkit
prefix for the filter
property, but it should have already worked in Firefox.
If you want to loop over the elements and remove the filter from the current element and add it back to the previous element, then you can use the following:
i % images.length
- This will get the index of the current element and then reset back to 0
when i
exceeds the number of images.
(curr - 1 < 0 ? images.length : curr) - 1
- Likewise, this will get the previous element by subtracting 1
from the current index or 1
from the total number of images if the index is -1
.
It would obviously be better to add/remove/toggle classes here and avoid inline styling, but nonetheless, this works for example purposes:
var images = document.querySelectorAll('img'),
i = 0;
function removeGreyscale() {
var curr = i % images.length,
prev = (curr - 1 < 0 ? images.length : curr) - 1;
// Remove grayscale filter from the current element
images[curr].style.webkitFilter = "grayscale(0)";
images[curr].style.filter = "grayscale(0)";
// Add grayscale filter to the previous element
images[prev].style.webkitFilter = "grayscale(1)";
images[prev].style.filter = "grayscale(1)";
i++;
}
setInterval(removeGreyscale, 1000);
img {
-webkit-filter: grayscale(1);
filter: grayscale(1);
}
<img src="//placehold.it/200/f00" />
<img src="//placehold.it/200/0f0" />
<img src="//placehold.it/200/00f" />
CSS only solution: http://jsfiddle.net/t2zaf1fk/2/
HTML:
<img src="//placehold.it/200/f00" />
<img src="//placehold.it/200/0f0" />
<img src="//placehold.it/200/00f" />
CSS:
img {
-webkit-animation: fade 3s linear 0 infinite;
-webkit-filter: grayscale(1);
}
img:nth-child(1) {
-webkit-animation-delay:1s;
}
img:nth-child(2) {
-webkit-animation-delay:2s
}
@-webkit-keyframes fade {
0% {
-webkit-filter: grayscale(1);
}
65% {
-webkit-filter: grayscale(1);
}
66% {
-webkit-filter: none;
}
100% {
-webkit-filter: none;
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With