image comparison slider
September 15, 2014 | 1 Feedback

Image Comparison Slider

A handy draggable slider to quickly compare 2 images, powered by CSS3 and jQuery.
Browser support
  • ie
  • Chrome
  • Firefox
  • Safari
  • Opera
9+

When you create a product page, there are some effective UX solutions that can be used to make the user ‘feel’ the product. A comparison image slider is one of those.  If you look at the Sony Ultra HD TV product page, they use this approach to emphasize the difference between their display resolution and a standard one. Google uses it to show how cool is a Google+ Photos filter.

Image credits: Unsplash.

Let’s dive into the code ;)

Creating the structure

We used a figure element to wrap our original image, the modified image (set as background of the div.cd-resize-img element) and the slider handle:

Adding style

While the original image is inserted inside the code and gives the correct dimentions to its container .cd-image-container, the modified image is added as background of the div.cd-resize-image. This element is set in position: absolute over the .cd-image-container and its width is changed while dragging the .cd-handle element (using jQuery) in order to reveal/hide the modified image.
The .cd-resize-image width is originally set to 0, and then changed to 50% when it  enters the viewport, using the .is-visible class which is added to the .cd-image-container (using jQuery). We also defined the cd-bounce-in animation to create a bounce effect.
This way, the animation will only start when the .cd-image-container is visible inside the viewport.

Events handling

To implement the slider functionality, we defined the drags() function to make the .cd-handle element draggable (credit to CSS-Tricks).
When the mouse is pressed over the .cd-handle element and moved, we update the .cd-handle left value according to the current mouse position (we have added a constrain to limit the movement inside its parent .cd-image-container) and change the div.cd-image-size width accordingly.

In order to add mobile support, we have been using jQuery mobile (specifically, the vmouse events which simulate the mouse events on a touch device).

As last effect, when the .cd-image-container element enters the viewport, we add the .is-visible class to animate its children.

Changelog

Sep 15, 2014
  • Resource released by CodyHouse

Claudia Romano

Web developer, fan of The Big Bang Theory and good food. Co-founder of Cody. You can follow her on Twitter.

  • Efren Castillo

    Sweet. Thanks!