Removing grayscale css filter from images using javascript

I am trying to iterate over some images and remove the 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 does not currently work.

+4
source share
2 answers

It looks like you need to smooth out the "f" in the property webkitFilter:

document.images[h].style.webkitFilter = "grayscale(1)";
document.images[h].style.filter = "grayscale(1)";

Chrome still requires a prefix -webkitfor the filterproperty , but it should have already worked in Firefox.


If you want to iterate over the elements and remove the filter from the current element and add it back to the previous element, you can use the following:

  • i % images.length - , reset 0, i .

  • (curr - 1 < 0 ? images.length : curr) - 1 - , , 1 1 , -1.

, // , , , :

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" />
Hide result
+5

CSS: 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;    
    }
}
+1

Source: https://habr.com/ru/post/1619670/


All Articles