Crossfade.js is a tiny (~3kb) jQuery plugin for crossfading images as you scroll down a page.

Try it. Scroll down.

Do it. I bet you won't do it.

It is, isn't it? Here's how to use it.

bower install crossfade.js

And initialize it…

$(function () {



  $('.crossfade').crossfade(options);



});

Options

start required The URL of the first (start) image. You can also define this property as a data-crossfade-start attribute on the element itself.
end required The URL of the second (end) image. You can also define this property as a data-crossfade-end attribute on the element itself.
threshold Default: 0.5
A number between 0 and 1 that determines how quickly the crossfade occurs as the element scrolls off-screen
backgroundPosition Default: 'center center'
Determines the positioning of the background images. Backgrounds are sized similarly to CSS's “background-size: cover”. This option determines along which edges the image is aligned.

Technical Details

Under the hood, Crossfade.js does the following…

  1. Preloads the start and ending images
  2. Generates a <canvas> element and appends it to our element. The canvas is automatically set to cover its parent, via absolute positioning.
  3. The starting and ending images are drawn into the <canvas> and, depending on the position of the element in the viewport, superimposed on top of one another.
  4. Images are redrawn using window.requestAnimationFrame, allowing for exceptionally performant rendering. Browsers that do not support window.requestAnimationFrame yet will fall back to a timeout loop.

Notes

Some things to keep in mind…

  1. The elements you initialize Crossfade.js on must be able to contain their children. Use CSS to set the position to “relative”, “absolute” or “fixed”, depending on your use case.
  2. Any content already inside the element you initialize Crossfade.js on will need to be set to “position: relative” to make sure it's visible above the injected <canvas> element:
    <div class="cover">
    
    
    
      <div class="cover-content" style="position: relative;">
    
        <h1>Make sure I'm above the background!</h1>
    
      </div>
    
    
    
      <!-- I get injected by crossfade.js -->
    
      <canvas></canvas> 
    
    
    
    </div>