Search code examples
jquerysvgfill

Change the fill of an svg as a progress bar passes in the background


I have a progress bar that drops in when the user scrolls down more than 100 pixels. The background of the progress bar fills with red. The progress bar container also contains an svg of a tree which is white.

How can I change the fill color of the svg as the progress bar passes behind it. So, if the progress bar is halfway through the back of the tree, the left half would be white and the right half would still be red. Is that even possible? I am using jQuery currently.

I mocked up a quick pen here: http://codepen.io/redbranchmedia/pen/aGfme

Here is the script I am using for the progress bar:

  // fills progress bar on scrolldown 

jQuery(document).on('ready', function() {  
  var winHeight = $(window).height(), 
      docHeight = $(document).height(),
      progressBar = $('progress'),
      max, value;

  /* Set the max scrollable area */
  max = docHeight - winHeight;
  progressBar.attr('max', max);

  jQuery(document).on('scroll', function(){
     value = $(window).scrollTop();
     progressBar.attr('value', value);
  });
});
// end progress bar

Solution

  • You're almost there. It is an animation trick to use a red tree behind a white tree. So when the white tree is unmasked, the red tree appears.

    Earlier revision answers the SO question, however it isn't 100% pixel accurate with various window width and window zoom (May be possible to fix it with more math). Hence this new update below.

    Update: New codepen example using gradient to gradually turn it white. Adjust the value 0.1 in (max*0.1) if you want it to turn white later