Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

removing greyscale css filter from images with javascript

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.

like image 316
Ollie_W Avatar asked Dec 13 '15 01:12

Ollie_W


2 Answers

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" />
like image 132
Josh Crozier Avatar answered Oct 25 '22 04:10

Josh Crozier


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;    
    }
}
like image 27
Scott van Looy Avatar answered Oct 25 '22 05:10

Scott van Looy