image comparison slider
September 15, 2014 | 73 Feedbacks

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 and the slider handle:

Adding style

The original image is used to give the correct dimentions to its container .cd-image-container; the modified image is inserted inside 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

May 02, 2016
  • Improved drag functionality
Sep 18, 2014
  • Modified image inserted in the HTML rather than as background-image in CSS
Sep 15, 2014
  • Resource released by CodyHouse

Claudia Romano

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

  • Efren Castillo

    Sweet. Thanks!

  • http://www.designjaunt.com Sanjeev Sharma

    Thank you!

  • benjibuls

    Very nice work, have been playing with something similar for my own project. Your example looks and works great. The only thing I did differently was allow the slider to go completely to the left or right by positioning the drag handle half over the edge of the inner image container. Then you can can completely hide or reveal one of the images.

    • Flip4Bytes

      Same, if anyone who isn’t too familiar with javascript wants to implement this modification then replace:

      minLeft = containerOffset + 10,
      maxLeft = containerOffset + containerWidth – dragWidth – 10;

      with

      minLeft = containerOffset – 22,
      maxLeft = containerOffset + containerWidth – dragWidth + 22;

      in the main.js

  • Flip4Bytes

    I find it odd that this was built in a way that the modified image is declared in the css instead of within the HTML. The way it is currently set up, it makes it a real pain when trying to have numerous before/after images on one page. Anyone find a good workaround for this?

    Looks great otherwise!

    Thanks

    • Claudia Romano

      Hi, thanks for the heads up! We’ve just uploaded a new version with the modified image inserted as image in the HTML rather than as background image in CSS. That should help! :)

      • Flip4Bytes

        Much better now! Just switched it out with Zurb’s “TwentyTwenty” option. This one looks MUCH better and it’s implemented in a much cleaner way. This tutorial couldn’t have come at a better time!

        Thanks so much and keep up the phenomenal work!

        • subintellect

          Hello,

          Can you describe how you modified this to support multiple sliders on the same page?

          Cheers!

          • Flip4Bytes

            All you have to do is duplicate more of the html section .

          • subintellect

            Did you find any way to improve performance in your experimenting?

          • Flip4Bytes

            Unfortunately no, not at the moment. It’s quite heavy on mobile even using pretty powerful devices. It seems to be alright on desktop though. I am not the best with JavaScript optimizations though. If anyone finds a good way to achieve this please do share, it would be pretty useful to us all.

            Cheers!

  • http://afroniquelyu.com/ afroniquely | shae

    I’m using Chrome on a Mac, and for some odd reason when I view the demo nothing shows up except 1 image. I don’t see any slider to view/preview a before-after style or any of that, just 1 static image.

  • gt3themes

    Hi there! Great slider, can I use it in the commercial projects, like wordpress themes for sale?

  • Тимофей Мельник

    ty for the idea

  • Guest

    Test

  • Akshay Bhimani

    nice Creativity :) (y) @romano_cla

  • http://jkspepper.tumblr.com/ jkspepper

    Hi guys, I’m a non-coder but would like to add this to a tumblr site. How best would I do this? Thanks

  • Geoffrey Fosson

    Wow. Great job Claudia! Thanks for sharing this..

  • Rainer

    Hi, is it possible to have the original/modified text below the images? Thank you for your help.

    • http://codyhouse.co Claudia Romano

      Hi Rainer, you may try changing the bottom position of the .cd-image-label (and remove the overflow: hidden from the .cd-resize-img). Hope this helps!

      • Rainer

        Hi Claudia, thank you for your quick response but unfortunately removing overflow: hidden doesn’t work, this makes the original image disappears completely. Any idea?

  • Lee

    It seems that these sliders aren’t able to work when placed inside a lightbox, any idea as to why? It appears as it should, but the mouseover and draggable events just seem to select the divs rather than interact in the usual way

    • http://codyhouse.co Claudia Romano

      Hi Lee, not sure why it’s not working in a lightbox. Do you have a live version to check?

      • Gabes

        Hi Claudia, thanks for the great code! I am having the same issue in trying to incorporate your work within a lightbox (in this case, Featherlight http://noelboss.github.io/featherlight/). Do you have any tips for doing so?

        • http://yugenelee.com/ Yugene Lee

          Did you all manage to add inside a lightbox?

  • Fonsoal Vasri

    Amazing Work

  • CybranM

    It looks great but is there any way to have the circle with a line behind it going from the top of the images to the bottom?
    I tried adding another .cd-handle2 in the css with 100% height and 2px wide and then inserting another inside the cd-handle . That didnt work though and I’m not familliar with java unfortunately. Anyone knows a way to add a line behind the circle handle?

    • http://codyhouse.co Claudia Romano

      Hi Cybran, you can try adding an ::after pseudo element to the .cd-resize-img. That should work!

      • CybranM

        I tried adding a ::after but didnt get it to work. In the end I added a div with an image in it inside the cd-handle div () and it allows me to have the handle be a line and then i made the image look like two arrows.
        I love how easy your image comparison slider is to use, compared to the other ones I tried this is by far the best.

  • trace1301t

    Hi, This is a fantastic effect and I’d love to use it on my wordpress site with some of my photography but I am not sure how I can make it work, I have copied the folder into my plugins but I can’t see it to change any settings. Please can you let me know what I am doing wrong.. ?

  • InternetMythBuster

    Hi, thank you for this wonderful piece of code, my own attempt was only marginally successful which was no surprise since I have exactly 0 web experience.

    If it’s not too much to ask, is it possible to not resize the picture into a small box? Let’s say suppose my work always uses a 1280×720 picture at all times and I want it to be displayed as is for comparisions.

    Thanks!

  • Accura

    i am creating the swiming pool template.. can i use this one as a banner (before clean and after clean) … and i would like to sell with the template

  • http://alikgriffin.com/ Alik Griffin

    This is really nice. I got it all working on my Drupal site with css except for one thing. The .cd-resize-img part of it seems to always load the image at 100% of the image size rather than scaling it to the display block. However the background image scales fine when resizing the browser window.

    Any suggestions?

    • http://codyhouse.co Claudia Romano

      Hi Alik, make sure the .cd-resize-img has an overflow: hidden. Hope this helps!

      • http://alikgriffin.com/ Alik Griffin

        Thanks for the quick reply. Overflow is hidden. The image outside of the display area is hidden, just the area that is visible is showing a 100% view of the image. I wonder if I have some other css code within my theme that is overriding the image property. Could that be a possibility?

        • http://codyhouse.co Claudia Romano

          That could be! Anyway make sure that the image has a max-width: none (and not max-width: 100%), width: auto and height: 100%. That should work.

          • http://alikgriffin.com/ Alik Griffin

            Thanks for the help and quick responses. I figured it out. I had to add !important; next to
            height: 100%.
            I remembered I had to do that to get images to scale with the browser window as part of my sites main css, so I applied it here too. Seems to work.

          • Brahime Y-ch

            Hii CLAUDIA
            please i want your help to add this quick view
            i’m waiting for your answer
            thnx in advance

  • V. Alfa Dionny

    This looks great, but why when I use, I should do refresh the browser again to see the results.If there is something wrong with jquery placement. Thank you for your help.

    • http://codyhouse.co Claudia Romano

      Hi, not sure what you mean by that. Is this an issue you’re experiencing with our demo and on which browser? Thanks!

      • Valentinus Alfa Dionny

        Thanks for quick reply.
        I’ve tried with another browser but the result was the same.
        For your demo no problem but when I use in my theme, the picture is not arranged be one frame but two, top and bottom. Whether this is because since there css code is wrong. Thanks.

        • http://codyhouse.co Claudia Romano

          Hi, please make sure to properly included the style.css file. Hope this helps!

  • Jonathan Hottart

    Very good but when I use with 70 images (.png total 2Mo) in one part. The system freeze (block). If I reduce the number of images it works. Could you help me ? (sorry for my bad english)

    • http://codyhouse.co Claudia Romano

      Hi Jonathan, actually there should be no problem with multiple images. Please make sure that your issue is not related to any other plugins/code.

      • Jonathan Hottart

        Thank you for your reply. The problem is not linked to the slider. Apparently it is not possible to superpose many .png so large. A big thank you for this beautiful slider.

  • Janna

    This is great! Is there a way to get the slider to work vertically (top to bottom) instead of horizontally?

  • http://misterk.me/ TheSupremus

    I have incorporated this into my website that I am working on, however it seems that the scripts aren’t being loaded-in for what ever reason. I am using WordPress and importing the files into a page.

    http://pave.misterk.me/before-after/

    Original

    Modified

  • http://nazarkin.su/ Nazarkin Roman

    Nice work! But this solution has a serious bug with performance: every click on .cd-handle creates a three new event listeners and after each move of handle count of event listeners will be increased, so this makes a big load to CPU.

    • Jesse

      You’re right, if you click on the handle several times it starts to lag a lot. What would you suggest to fix this? I’ve tried using off() to remove the event handlers, but it doesn’t seem to help.

      • http://nazarkin.su/ Nazarkin Roman

        I’ve used one() function and event names with postfix(to easily unbind them). My improved version of drags() function – https://gist.github.com/NazarkinRoman/4086b39dc6d02d25f459

        • Jesse

          That’s a nice solution, it works perfectly. Thanks!

        • http://codyhouse.co Claudia Romano

          Hi Nazarkin, thanks for the heads-up! we’re gonna fix this ;)

        • Daniel

          Рома, позволь тебя спросить/попросить о помощи, а как сделать так, чтобы не за “cd-handle” двигать слайдер, а либо за всю высоту перетягивать полоску, либо мышкой как тут http://www.jqueryscript.net/demo/jQuery-Plugin-For-Image-Comparison-with-Mouse-Interaction-DiffWidget-js/
          я не “настоящий сварщик”, поэтому прошу совета/помощи

  • http://1871.by/ KingStakh

    Nice plugin, but not work with touch screens

  • wt

    Hi im running fullPage.js with with it but slider becomes unusable. If I shift the js files to the bottom of the html, it would work but it breaks fullPage.js. any suggestion?

  • Roedolf Nieuwenhuis

    Awesome slider, I’m looking for something similar but with added functionality like a image / date selector where users can select which two images they would like to see for the slider? Is it possible?

  • neo

    great!!!

  • Mika Mika

    hi how can I use two or more images with this plugin?

  • Bart McLaughlin

    Hello! This slider is awesome. Does anyone know how I can make it 100% browser width and height?

  • Lu_B_H

    Awesome, thanks Claudia.

  • MDisseny

    Hi Claudia! Thanks for sharing this great slider. I’ve been testing it for a while and love it. However I get an error with the updateLabel function:

    Uncaught TypeError: Cannot read property ‘offset’ of undefined

    What am I doing wrong? I guess it must be obvious but I can’t find the issue. Any help would be appreciated, thanks.

    Cheers!!!

  • http://www.bdthemes.com/ Selim Rana

    Hello, can you add vertical option? not only horizontal.

  • Luke

    Hi Claudia – I’ve managed to get the image comparison slider up and running on our site – A huge thumbs up as all is working perfectly as per your demo. However, we have noticed that the dragable element is thrown out of sync after resizing the browser window (if it has been previously utilised – ie. drag, resize window, drag), can you think of a quick solution to avoid this?

    I’m guessing the issue lies in the js and thats unfortunately its far from being my strong suit ;(

    Cheers!

  • danickgevry

    Hi Claudia,

    I had some issues getting the slider to work on touch device. Touch events were not working so I switched to “touchstart”, “touchmove” and “touchend” instead of the “vmouse” events. Then all the pageX values used in the code were returning NaN on touch devices so here is the code I user to get the right pageX values:

    var pageX = (e.type.toLowerCase() === ‘mousedown’) ? e.pageX : e.originalEvent.touches[0].pageX;

    Hope this can help anyone!

    Best regards.

  • Filippo Rovelli

    Hi Claudia,
    thanks for your sharing. It’s fantastic. Everything work’s fine. But I have a problem with PJAX. When I call up the page, the slider doesn’t work. May be you have some solution? May be you have some reload code to put in my PJAX script?
    Thank you