Start building

Guides

A Shopify before and after slider that works with a thumb and a keyboard

Plenty of comparison sliders look right on a desktop and fail once you put a thumb or a Tab key on them. This one starts from those two tests.

The Klorr teamUpdated 7 min read

  • Before and after
  • Images
  • Accessibility
  • No app

Key takeaways

  • A visually hidden input type="range" gives you keyboard control and screen reader support at no cost. The pointer code only has to set its value.
  • touch-action: pan-y on the image area lets a sideways drag move the seam while an up-and-down swipe still scrolls the page.
  • Reveal with clip-path on one image and leave its size alone, so the photo doesn't squash or shift as the seam moves.
  • The two photos have to match in framing and light. If they don't, no slider code can make the comparison convincing.

Before you pick up code from a tutorial or an app, run any comparison slider through these four checks. They take a minute on a phone and a laptop, and they catch most of what is wrong with the versions you find online.

  1. Scroll: put your thumb on the image and swipe up. The page should scroll. Sliders that capture all touch trap people halfway down the page.
  2. Keyboard: press Tab until you reach it, then use the arrow keys. A slider built only from pointer events can't be reached at all.
  3. Screen reader: turn on VoiceOver or TalkBack and find it. You should hear a name and a value, and both photos should have a description.
  4. Grab: press anywhere on the image, not only on the handle, and drag. A small handle is hard to hit with a thumb, and the image is the obvious target.

The section below passes all four, using a native range input for the parts browsers already do well and a few lines of pointer code for the rest.

The complete section

sections/before-after-slider.liquid
{%- liquid
  assign loading = 'lazy'
  if section.index == 1
    assign loading = 'eager'
  endif
  assign before_alt = section.settings.before_alt | default: section.settings.before_image.alt
  assign after_alt = section.settings.after_alt | default: section.settings.after_image.alt
-%}

<div class="ba-{{ section.id }}">
  {%- if section.settings.heading != blank -%}
    <h2 class="ba-heading">{{ section.settings.heading | escape }}</h2>
  {%- endif -%}

  <before-after
    class="ba-stage"
    style="--pos: {{ section.settings.start }}%"
    data-value-text="{{ section.settings.value_text | escape }}"
  >
    <div class="ba-layer">
      {%- if section.settings.after_image != blank -%}
        {{ section.settings.after_image | image_url: width: 1800 | image_tag: loading: loading, alt: after_alt, widths: '600, 900, 1200, 1800', sizes: '(min-width: 1000px) 960px, 100vw', class: 'ba-img' }}
      {%- else -%}
        {{ 'lifestyle-2' | placeholder_svg_tag: 'ba-img' }}
      {%- endif -%}
    </div>
    <div class="ba-layer ba-before">
      {%- if section.settings.before_image != blank -%}
        {{ section.settings.before_image | image_url: width: 1800 | image_tag: loading: loading, alt: before_alt, widths: '600, 900, 1200, 1800', sizes: '(min-width: 1000px) 960px, 100vw', class: 'ba-img' }}
      {%- else -%}
        {{ 'lifestyle-1' | placeholder_svg_tag: 'ba-img' }}
      {%- endif -%}
    </div>

    <span class="ba-label ba-label--before">{{ section.settings.before_label | escape }}</span>
    <span class="ba-label ba-label--after">{{ section.settings.after_label | escape }}</span>

    <input
      class="ba-range"
      type="range"
      min="0"
      max="100"
      step="1"
      value="{{ section.settings.start }}"
      aria-label="{{ section.settings.slider_label | escape }}"
    >
    <span class="ba-handle" aria-hidden="true">
      <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 5 2 10l5 5M13 5l5 5-5 5"/></svg>
    </span>
  </before-after>
</div>

<style>
  .ba-{{ section.id }} {
    padding: {{ section.settings.padding }}px 16px;
    background: {{ section.settings.background }};
    color: {{ section.settings.ink }};
  }
  .ba-{{ section.id }} .ba-heading { margin: 0 0 20px; text-align: center; }
  .ba-{{ section.id }} .ba-stage {
    position: relative;
    display: block;
    max-width: 960px;
    margin: 0 auto;
    aspect-ratio: {{ section.settings.aspect }};
    overflow: hidden;
    border-radius: 12px;
    cursor: ew-resize;
    user-select: none;
    -webkit-user-select: none;
    touch-action: pan-y;
  }
  .ba-{{ section.id }} .ba-layer { position: absolute; inset: 0; }
  .ba-{{ section.id }} .ba-before { clip-path: inset(0 calc(100% - var(--pos)) 0 0); }
  .ba-{{ section.id }} .ba-img {
    display: block;
    width: 100%;
    height: 100%;
    object-fit: cover;
    pointer-events: none;
  }
  .ba-{{ section.id }} .ba-label {
    position: absolute;
    top: 12px;
    padding: 4px 10px;
    border-radius: 99px;
    background: rgba(0, 0, 0, .65);
    color: #fff;
    font-size: 13px;
    pointer-events: none;
  }
  .ba-{{ section.id }} .ba-label--before { left: 12px; }
  .ba-{{ section.id }} .ba-label--after { right: 12px; }
  .ba-{{ section.id }} .ba-range {
    position: absolute;
    inset: 0;
    width: 100%;
    height: 100%;
    margin: 0;
    opacity: 0;
    pointer-events: none;
  }
  .ba-{{ section.id }} .ba-handle {
    position: absolute;
    top: 50%;
    left: var(--pos);
    display: grid;
    place-items: center;
    width: 44px;
    height: 44px;
    border-radius: 50%;
    background: {{ section.settings.handle }};
    color: {{ section.settings.handle_ink }};
    transform: translate(-50%, -50%);
    pointer-events: none;
  }
  .ba-{{ section.id }} .ba-handle::before {
    content: "";
    position: absolute;
    top: -100vh;
    bottom: -100vh;
    left: 50%;
    width: 2px;
    margin-left: -1px;
    background: {{ section.settings.handle }};
    z-index: -1;
  }
  .ba-{{ section.id }} .ba-range:focus-visible + .ba-handle {
    outline: 3px solid {{ section.settings.ink }};
    outline-offset: 3px;
  }
</style>

<script>
  if (!customElements.get('before-after')) {
    customElements.define('before-after', class extends HTMLElement {
      connectedCallback() {
        var stage = this;
        var range = this.querySelector('.ba-range');
        var template = this.dataset.valueText;
        var dragging = false;

        function show(value) {
          stage.style.setProperty('--pos', value + '%');
          range.value = value;
          range.setAttribute('aria-valuetext', template.replace('[percent]', value));
        }
        function fromPointer(event) {
          var box = stage.getBoundingClientRect();
          var share = (event.clientX - box.left) / box.width;
          show(Math.round(Math.max(0, Math.min(1, share)) * 100));
        }

        range.addEventListener('input', function () { show(range.value); });
        stage.addEventListener('pointerdown', function (event) {
          dragging = true;
          stage.setPointerCapture(event.pointerId);
          range.focus({ preventScroll: true });
          fromPointer(event);
        });
        stage.addEventListener('pointermove', function (event) {
          if (dragging) fromPointer(event);
        });
        ['pointerup', 'pointercancel'].forEach(function (name) {
          stage.addEventListener(name, function () { dragging = false; });
        });
        show(range.value);
      }
    });
  }
</script>

{% schema %}
{
  "name": "Before and after slider",
  "tag": "section",
  "settings": [
    { "type": "text", "id": "heading", "label": "Heading", "default": "See the difference" },
    { "type": "image_picker", "id": "before_image", "label": "Before photo" },
    { "type": "text", "id": "before_alt", "label": "Describe the before photo", "info": "For screen readers. Uses the image's own alt text if empty." },
    { "type": "text", "id": "before_label", "label": "Before label", "default": "Before" },
    { "type": "image_picker", "id": "after_image", "label": "After photo" },
    { "type": "text", "id": "after_alt", "label": "Describe the after photo" },
    { "type": "text", "id": "after_label", "label": "After label", "default": "After" },
    { "type": "range", "id": "start", "label": "Starting position", "min": 0, "max": 100, "step": 5, "unit": "%", "default": 50 },
    {
      "type": "select",
      "id": "aspect",
      "label": "Shape",
      "default": "4 / 3",
      "options": [
        { "value": "1 / 1", "label": "Square" },
        { "value": "4 / 3", "label": "Landscape" },
        { "value": "16 / 9", "label": "Wide" },
        { "value": "3 / 4", "label": "Portrait" }
      ]
    },
    { "type": "text", "id": "slider_label", "label": "Slider name for screen readers", "default": "Compare before and after photos" },
    { "type": "text", "id": "value_text", "label": "Slider value for screen readers", "default": "Showing [percent]% of the before photo", "info": "[percent] is replaced with the current position." },
    { "type": "range", "id": "padding", "label": "Space above and below", "min": 0, "max": 80, "step": 4, "unit": "px", "default": 40 },
    { "type": "color", "id": "background", "label": "Background", "default": "#ffffff" },
    { "type": "color", "id": "ink", "label": "Text", "default": "#1a1a1a" },
    { "type": "color", "id": "handle", "label": "Handle and line", "default": "#ffffff" },
    { "type": "color", "id": "handle_ink", "label": "Handle arrows", "default": "#1a1a1a" }
  ],
  "presets": [ { "name": "Before and after slider" } ]
}
{% endschema %}

Add it with the usual steps for a custom section, pick your two photos and describe each one in the alt fields. Until then it shows Shopify's placeholder drawings, which is why the section isn't blank when first added.

How each check is handled

The range input does the accessibility work

The range covers the stage with opacity: 0, invisible but still in the tab order. Arrow keys, Home and End all work with no script of ours. Screen readers announce it as a slider using the aria-label, and aria-valuetext turns "60" into "Showing 60% of the before photo". The visible handle gets its focus ring from .ba-range:focus-visible + .ba-handle, so keyboard users can see where they are even though the real control is invisible. If you edit the markup, that + needs the handle to come straight after the input.

Why not let the range handle dragging too?

That's the common shortcut, and it's tempting because it needs no pointer code. Its weaknesses show up on touch screens. Safari on iPhone has historically moved a range input only when the drag starts on the thumb, so a thumb on the photo does nothing. Styling a giant invisible thumb also leaves the seam slightly off your finger, because browsers keep the thumb inside the track at both ends. So this section sets pointer-events: none on the range and handles pointers on the stage instead.

One CSS property keeps page scrolling alive

touch-action: pan-y tells the browser that vertical swipes belong to the page and everything else belongs to us. A vertical swipe scrolls, and the browser sends pointercancel so the drag ends cleanly. Leave this out and either a phone scrolls the page as you drag, or you end up calling preventDefault and trapping people on the image. The pointer capture in pointerdown means a drag that wanders off the edge keeps tracking.

Clipping leaves the photo still

clip-path: inset(0 calc(100% - var(--pos)) 0 0) hides the right part of the before photo without changing its size. Older techniques animate the width of a wrapper, which either squashes the image or needs its width set again on resize. Here both photos stay exactly where they are, and only one custom property changes as you drag, so nothing in the page has to be laid out again.

Surviving the theme editor

Shopify re-renders a section each time a setting changes, and asks themes to re-run their JavaScript on `shopify:section:load`. A custom element handles that by itself: connectedCallback runs each time the new markup is inserted, and the element's own listeners go away with the old one. Nothing moves on its own, so there's no animation to switch off for people who ask for reduced motion. If you add a one-time sweep to hint that the seam moves, wrap it in a prefers-reduced-motion check.

Image handling

Both photos are always loaded, since the comparison needs them, so a slider costs two images. Keep the width sensible: sizes tells the browser the display size and widths gives it options, so a phone doesn't fetch 1800px. If the section is first on the page it's probably your largest paint, so the Liquid at the top sets loading to eager there. Everywhere else it's lazy.

object-fit: cover crops each photo to the chosen shape around the center. If the subject sits off-center, set a focal point on the image in Shopify's file editor and apply image.presentation.focal_point as an object-position on both photos. Use the same point on each, or your crops won't line up.

Shooting the photos, which matters more than the code

A slider makes any difference between two photos obvious, including differences you didn't intend. When the before was shot on a phone in a dim garage and the after in a studio, shoppers can see the lighting did the work, and they're right to distrust it.

  • Fix the camera on a tripod, or mark where you stood and held it. The seam only reads well if features line up across it.
  • Match the distance, angle and light. Shoot both at the same time of day if using daylight.
  • Export at the same pixel size and aspect ratio, and edit both with the same settings.
  • Check alignment before uploading: stack the pictures in any editor at 50% opacity. A ghosted edge will show up as a jump when the seam crosses it.
  • Pick a subject where the change is visible at phone size. A subtle improvement needs a tight crop.
  • Describe the change in the alt text. "Scratched oak table top before refinishing" tells a screen reader user what a picture can't.

More than one comparison, and when to look elsewhere

To show several pairs, add the section several times, which is the simplest route and fine for two or three. For a longer list, move the photo settings from the section into a block, wrap each stage in a for block in section.blocks loop with {{ block.shopify_attributes }}, and show them in a grid. Each pair is another two images, so keep only your strongest few above the fold. For a product-specific pair, connect the image settings to a metafield with dynamic sources and put the section on the product template.

A before and after photo comparison where the seam bends like a pulled string under the pointer and settles with a wobble
Before & After Slider (€7, or €5 with a plan) is built on a native range input too, with more character. Look at the seam as it's dragged: it bows and settles on a spring, and the labels fade according to how much of each photo is showing.

An app is the better fit if customers submit their own before and after photos, because that needs uploads, moderation and storage. A theme section only shows what you've picked in the editor. For anything in between, such as a slider that sits inside a product tab or compares three stages, you can write it from the code above, or describe it to Klorr's Liquid code generator.

Questions, answered

How do I add a before and after slider to Shopify?

Create a new section file with the code in this post, then add the section in the theme editor and pick your two photos. It works in any Online Store 2.0 theme, and no app is needed.

Why doesn't my before and after slider work on mobile?

Usually it's one of two things. Without touch-action: pan-y, the page and the slider fight over a swipe. And sliders that rely on a native range for dragging may only respond when you start on the small thumb. Handle pointer events on the image instead.

Can a before and after slider be used with a keyboard?

Yes, if it includes a real control. A range input, even a visually hidden one, gives Tab focus and arrow key movement. Show a focus ring on the visible handle so users can see it's selected.

What size should before and after photos be?

Use the same pixel dimensions and aspect ratio for both. Around 1800px wide is plenty for a full-width section, since Shopify serves smaller versions to smaller screens through the image_url filter and srcset.

Do before and after sliders slow down a Shopify page?

They add two images and a little script. Use lazy loading if the section is below the first screen, and responsive widths. There is no need for a library, as the movement is one CSS variable.

Get the whole section written for you

Describe the section you want. Klorr writes the Liquid, the CSS, the schema and every theme-editor setting — code that lives in your theme and stays yours.