< BACK TO COMPONENTS

Build an Image Comparison Slider: HTML, CSS, JavaScript Tutorial (Source Code)

Faraz

By Faraz -

Learn how to craft a seamless image comparison slider using HTML, CSS, and JavaScript with our easy tutorial. Perfect for web developers at any level.


Build an Image Comparison Slider HTML, CSS, JavaScript Tutorial.jpg

Welcome to our step-by-step tutorial on creating an interactive image comparison slider using HTML, CSS, and JavaScript. In this guide, we'll walk you through the process of building a simple yet powerful slider that allows users to compare images effortlessly. Whether you're a beginner looking to dive into web development or an intermediate developer seeking a practical project, this tutorial is tailored for you.


The focus of this tutorial is on simplicity and effectiveness. No prior coding experience is necessary; we'll guide you through each step, making it easy to grasp the concepts and implement them in your own projects. By the end of this tutorial, you'll have a functional image comparison slider ready to enhance your web development projects. Let's get started!

Source Code

Step 1 (HTML Code):

Begin by setting up the HTML structure for your image comparison slider. Use a straightforward HTML layout to provide a foundation for your project.


How to:


  1. Open your preferred code editor.
  2. Create a new HTML file.
  3. Set up the basic HTML structure with the necessary tags.

Let's break down the code:


1. <!DOCTYPE html>: Declares the HTML version being used, which is HTML5 in this case.


2. <html lang="en">: Defines the root element of the HTML document and specifies the language as English.


3. <head>: Contains meta-information about the HTML document, such as character set, viewport settings, and links to external resources.


  • <meta charset="UTF-8">: Specifies the character encoding for the document as UTF-8, which is a widely used character encoding for web pages.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge">: Suggests the latest Internet Explorer rendering engine to be used to render the webpage in compatibility mode.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Sets the viewport properties, ensuring the page adapts to the device's screen width and sets the initial zoom level to 1.0.
  • <title>Image Comparison Slider</title>: Sets the title of the webpage, which is displayed in the browser's title bar or tab.
  • <link rel="stylesheet" href="styles.css">: Links an external stylesheet (styles.css) to the HTML document, which is used for styling the webpage.

4. <body>: Contains the content of the webpage.


  • <div class="compare">: Defines a container with the class "compare" to hold the image comparison slider.
  • <section class="before">: Represents the "before" image in the comparison slider.
  • <img src="https://assets.codepen.io/2585/Runner.svg" alt="" />: Embeds an image with the source specified as "https://assets.codepen.io/2585/Runner.svg" and an empty alt attribute.
  • <section class="after">: Represents the "after" image in the comparison slider.
  • <img src="https://assets.codepen.io/2585/Roboto.svg" alt="" />: Embeds an image with the source specified as "https://assets.codepen.io/2585/Roboto.svg" and an empty alt attribute.
  • <input type="range" id="range" step="0.1">: Adds an input range slider with the id "range" and a step of 0.1. This slider is used to control the position of the comparison between the "before" and "after" images.
  • <script src="script.js"></script>: Includes an external JavaScript file (script.js) at the end of the body, which contains scripts for interactivity or additional functionality on the webpage.

Step 2 (CSS Code):

Now, let's make your image slider visually appealing. Add styles using CSS to enhance the user experience and give your slider a polished look.


How to:


  1. Link your CSS file to the HTML document.
  2. Define styles for the container, images, and slider controls.

Let's break down the code:


@layer demo {...}


1. .compare: This class represents a container with a grid display. All direct children of this container are set to occupy the first row and column of the grid.


2. > * (Universal Selector): Sets all direct children of the .compare class to occupy the first row and column of the grid.


3. > section: Styles any direct children of .compare that are <section> elements with a grid display, and centers their content.


4. .before and .after: These classes define masks using linear gradients. The masks create a visual effect where the content appears divided, with a variable position specified by the --pos CSS variable.


5. > input[type="range"]: Styles any direct children of .compare that are input elements with type "range." It sets various styles, including a transparent background and a customized appearance for the slider thumb. The slider thumb is customized for both WebKit and Gecko (Firefox) browsers.


@layer demo.support {...}


1. Universal Selector (*): Sets the box-sizing property to border-box and removes any default margin for all elements.


2. html: Sets the block size to 100% and specifies the color scheme as dark and light.


3. body: Styles the body element with a minimum block size of 100%, sets the font family to system-ui and sans-serif, and uses grid display.

@layer demo {
  .compare {
    display: grid;
    
    > * {
      grid-area: 1 / 1;
    }
    
    > section {
      display: grid;
      place-content: center;
    }
    
    .before {
      mask: linear-gradient(to right, #000 0, var(--pos, 50%), #0000 0);
    }

    .after {
      mask: linear-gradient(to right, #0000 0, var(--pos, 50%), #000 0);
    }

    > input[type="range"] {
      z-index: 1;
      appearance: none;
      background: transparent;
      cursor: pointer;
      -webkit-tap-highlight-color: transparent;

      &::-webkit-slider-thumb {
        appearance: none;
        inline-size: 4px;
        block-size: 100dvh;
        background-color: CanvasText;
      } 

      &::-moz-range-thumb {
        appearance: none;
        inline-size: 4px;
        block-size: 100dvh;
        background-color: CanvasText;
      }
    }
  }
  
  img {
    max-block-size: 80dvh;
    max-inline-size: 100%;
  }
}

@layer demo.support {
  * {
    box-sizing: border-box;
    margin: 0;
  }

  html {
    block-size: 100%;
    color-scheme: dark light;
  }

  body {
    min-block-size: 100%;
    font-family: system-ui, sans-serif;
    display: grid;
  }
} 

Step 3 (JavaScript Code):

Make your slider dynamic by incorporating JavaScript. This step will enable users to interact with the images, creating an engaging and responsive experience.


How to:


  1. Link your JavaScript file to the HTML document.
  2. Write functions to handle user interactions and update the slider accordingly.

Let's break down the code:


1. range.oninput: This part indicates that the event listener is triggered when the input event occurs on the range element. The oninput event occurs when the value of an input element is changed.


2. () =>: This is an arrow function in JavaScript, used here as a callback function. It will be executed when the oninput event occurs.


3. document.body.style.setProperty('--pos', range.value + '%'): This line of code sets a CSS variable (--pos) on the body element of the HTML document. The value of the variable is set to the current value of the range input (range.value), concatenated with the '%' symbol to make it a valid CSS percentage value.

range.oninput = () =>
  document.body.style.setProperty('--pos', range.value + '%')

Final Output:

Build an Image Comparison Slider HTML, CSS, JavaScript Tutorial.gif

Conclusion:

Congratulations! You've successfully created a simple image comparison slider using HTML, CSS, and JavaScript. This tutorial provides a solid foundation for your journey into front-end web development. Experiment, customize, and integrate this slider into your projects for an enhanced user experience. Happy coding!


Code by: Adam Argyle

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Related Post