0

At the moment I have an image that is grayscaled until hover and then it fades into full color. I achieved this effect with this CSS that I found on another post here.

img.grayscale {
  filter: url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\'>
  <filter      id=\'grayscale\'>
  <feColorMatrix type=\'matrix\' values=\'0.3333 0.3333 0.3333 0 0    0.3333 0.3333 0.3333 0 0 0.3333 0.3333 0.3333 0 0 0 0 0 1 0\'/>
  </filter></svg>#grayscale"); /* Firefox 3.5+ */
  filter: gray; /* IE6-9 */
  -webkit-filter: grayscale(100%); /* Chrome 19+ & Safari 6+ */
   }

img.grayscale:hover {
 filter: none;
 -webkit-filter: grayscale(0%);
}

but now I am hoping to have the image remain grayscale until it comes into view when the user scrolls down on it's section on my one pager website. Then when the user scrolls past the image, it will fade back into grayscale once more.

Basically the exact same effect found on www.hubspot.com's Marketing Platform and Sales Platform section. How would I be able to achieve this effect?

Many thanks for all your help.

Nelu
  • 16,644
  • 10
  • 80
  • 88
  • Listen on the `window.scrollTop` value, and update the class for the image when it is `>=` the position you'd like your image to swap to non-grayscale. – Josh Burgess Nov 26 '14 at 19:05

1 Answers1

0

You can do something like this:

var offset = 100;

$(window).scroll(function(){

    var $elem = $(".magic"),
        topDist = $elem.offset().top - $(this).scrollTop(),
        bottomDist = $elem.offset().top + $elem.height() - $(this).scrollTop();

    if (topDist < offset && bottomDist > offset) {
        // (turn on colors)
        $elem.css("background-color","red");
    } else {
        // (turn off colors)
        $elem.css("background-color","gray");
    }
});

jsFiddle

Or, for a better result you may need to compare the bottom of the element with the bottom of the viewport. This answer may help.

Community
  • 1
  • 1
Nelu
  • 16,644
  • 10
  • 80
  • 88