Motion & Games

Build an Image Comparison Slider for E-Learning

Learn how to build an accessible image comparison slider for e-learning that works in Rise 360, Storyline, SharePoint, or as a standalone page. This interactive before-and-after slider includes mouse, touch, and keyboard support for all learners.

By Nathan Stoker · Published Jul 5, 2026 · Updated Nov 8, 2026 · 12 min read

Download

Build an Image Comparison Slider for E-Learning

Before and after comparisons are powerful teaching tools. Whether you're showing the results of a procedure, demonstrating software changes, or revealing the impact of a decision, seeing two states side by side creates immediate understanding. An image comparison slider lets learners interactively explore these differences at their own pace.

In this tutorial, you'll learn how to create a fully accessible image comparison slider for e-learning that works in Articulate Rise 360, Articulate Storyline (as a web object), SharePoint, or as a standalone webpage. The slider includes mouse, touch, and keyboard support, plus full ARIA accessibility for screen reader users.

Check out the demo and download the file in the header to follow along.

Why Use an Image Comparison Slider in Training?

Visual comparisons create instant comprehension that text descriptions simply cannot match. When learners can drag a slider to reveal changes, they engage actively with the content rather than passively viewing static images.

Medical and healthcare training benefits enormously from before-and-after comparisons. Show tissue changes, treatment progressions, or anatomical differences. Learners can study transitions at their own pace, moving the slider back and forth to understand subtle variations.

Manufacturing and quality control training uses comparison sliders to highlight defects versus acceptable products. Rather than describing what to look for, show learners exactly what distinguishes a pass from a fail.

Software training demonstrates interface changes, feature updates, or the results of specific actions. Users see precisely what clicking that button or changing that setting accomplishes.

The cognitive theory of multimedia learning supports this approach. When verbal and visual information work together, learning improves. An interactive slider adds motor engagement, creating even stronger memory encoding.

How the Image Comparison Slider Works

This interaction overlays two images on top of each other. The "before" image sits in a clipped container that expands and contracts as the slider moves. The "after" image serves as the background, revealing progressively as the overlay shrinks.

A vertical line and circular drag handle indicate the current position. Labels identify which side shows "before" and which shows "after." The slider responds to mouse drags, touch gestures, and keyboard commands.

Key Features Overview

The interaction includes accessibility features that make it compliant with WCAG guidelines and usable by all learners.

Mouse and Touch Support: Learners can drag the slider button or click anywhere on the image to jump to that position. Touch devices work seamlessly with the same interactions.

Full Keyboard Navigation: Screen reader users and those who prefer keyboard navigation can tab to the slider, then use arrow keys for fine adjustments, Page Up and Page Down for larger jumps, and Home and End to go to extremes.

ARIA Attributes: The slider announces its current position to screen readers, describing what percentage of each image is visible. As learners adjust the position, live updates keep assistive technology informed.

Responsive Design: The slider adapts to any container width while maintaining image aspect ratios. It looks great on desktop monitors, tablets, and mobile phones.

Where You Can Use This Interaction

The same HTML file works across multiple platforms without modification.

Articulate Rise 360

Rise 360 accepts multimedia web content blocks that load external HTML files. Upload your slider files to a web server or cloud storage, then embed using the iframe URL.

To add the slider to Rise:

  1. Upload your HTML file and both images to cloud storage or your LMS

  2. In Rise, add a Multimedia block and select "Embed"

  3. Paste the URL to your HTML file

  4. Set appropriate dimensions (recommended: 800 pixels wide minimum)

Rise 360 automatically handles responsive behavior within its lesson structure.

Articulate Storyline

Storyline supports web objects that display HTML content directly on slides. This approach gives you precise control over placement and timing.

To add the slider to Storyline:

  1. Create a folder containing index.html and your two images

  2. In Storyline, insert a Web Object and point it to your folder

  3. Size the web object to fit your slide layout

  4. Set display options (show in slide, new browser window, or lightbox)

For more details on web objects, see the Articulate documentation on adding web objects.

SharePoint and Standalone Use

SharePoint modern pages support embedding HTML content through iframe web parts. You can also host the slider on any web server and link to it directly, or open the HTML file locally in a browser for testing.

Understanding the Complete Code

The slider uses pure HTML, CSS, and JavaScript with no external dependencies beyond Bootstrap for basic styling. This keeps the file size small and eliminates compatibility concerns.

Below is the complete code. Copy this into a file named index.html, place your two images in the same folder, and update the image source paths.

Complete Code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Image Comparison Slider</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.3.2/css/bootstrap.min.css" rel="stylesheet">
    <style>
        body {
            background-color: #f8f9fa;
            padding: 20px;
        }
        
        .comparison-container {
            position: relative;
            width: 100%;
            max-width: 800px;
            margin: 0 auto;
            overflow: hidden;
            border-radius: 10px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        
        .comparison-container img {
            display: block;
            width: 100%;
            height: auto;
            pointer-events: none;
        }
        
        .img-overlay {
            position: absolute;
            top: 0;
            left: 0;
            width: 50%;
            height: 100%;
            overflow: hidden;
        }
        
        .img-overlay img {
            width: auto;
            height: auto;
            min-width: 100%;
            max-width: none;
            position: absolute;
            left: 0;
            top: 0;
        }
        
        .slider-button {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 60px;
            height: 60px;
            background-color: white;
            border: 3px solid #0d6efd;
            border-radius: 50%;
            cursor: ew-resize;
            z-index: 10;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 24px;
            color: #0d6efd;
            user-select: none;
        }
        
        .slider-line {
            position: absolute;
            top: 0;
            left: 50%;
            width: 3px;
            height: 100%;
            background-color: white;
            transform: translateX(-50%);
            pointer-events: none;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.5);
        }
        
        .label {
            position: absolute;
            top: 20px;
            padding: 8px 16px;
            background-color: rgba(0, 0, 0, 0.7);
            color: white;
            border-radius: 5px;
            font-size: 14px;
            font-weight: 600;
            z-index: 5;
        }
        
        .label-before {
            left: 20px;
        }
        
        .label-after {
            right: 20px;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1 class="text-center mb-4">Image Comparison Slider</h1>
        
        <div class="comparison-container" id="comparisonContainer" role="group" aria-label="Image comparison slider">
            <!-- After Image (Background) -->
            <img src="after.jpg" alt="After image: Colorful landscape with mountains" id="afterImg">
            
            <!-- Before Image (Overlay) -->
            <div class="img-overlay" id="imgOverlay" aria-hidden="true">
                <img src="before.jpg" alt="Before image: Desert landscape with sand dunes" id="beforeImg">
            </div>
            
            <!-- Slider Line -->
            <div class="slider-line" id="sliderLine" aria-hidden="true"></div>
            
            <!-- Slider Button -->
            <div class="slider-button" 
                 id="sliderButton" 
                 role="slider" 
                 aria-label="Image comparison slider"
                 aria-valuemin="0" 
                 aria-valuemax="100" 
                 aria-valuenow="50"
                 aria-valuetext="50 percent - showing half before and half after image"
                 tabindex="0">⇔</div>
            
            <!-- Labels -->
            <div class="label label-before" aria-hidden="true">Before</div>
            <div class="label label-after" aria-hidden="true">After</div>
        </div>
        
        <p class="text-center text-muted mt-3">
            Drag the slider to compare the images<br>
            <small>Keyboard users: Tab to focus the slider, then use Arrow keys (←/→), Home/End, or Page Up/Down to navigate</small>
        </p>
    </div>

    <script>
        const container = document.getElementById('comparisonContainer');
        const overlay = document.getElementById('imgOverlay');
        const sliderButton = document.getElementById('sliderButton');
        const sliderLine = document.getElementById('sliderLine');
        let isDragging = false;

        function updateSlider(x) {
            const rect = container.getBoundingClientRect();
            let position = x - rect.left;
            
            // Constrain position within container
            position = Math.max(0, Math.min(position, rect.width));
            
            const percentage = (position / rect.width) * 100;
            
            overlay.style.width = percentage + '%';
            sliderButton.style.left = percentage + '%';
            sliderLine.style.left = percentage + '%';
            
            // Update ARIA attributes for screen readers
            const roundedPercentage = Math.round(percentage);
            sliderButton.setAttribute('aria-valuenow', roundedPercentage);
            sliderButton.setAttribute('aria-valuetext', `${roundedPercentage} percent - showing ${roundedPercentage}% before image and ${100 - roundedPercentage}% after image`);
        }

        sliderButton.addEventListener('mousedown', (e) => {
            isDragging = true;
            e.preventDefault();
        });

        document.addEventListener('mousemove', (e) => {
            if (isDragging) {
                updateSlider(e.clientX);
            }
        });

        document.addEventListener('mouseup', () => {
            isDragging = false;
        });

        // Touch events for mobile
        sliderButton.addEventListener('touchstart', (e) => {
            isDragging = true;
            e.preventDefault();
        });

        document.addEventListener('touchmove', (e) => {
            if (isDragging) {
                updateSlider(e.touches[0].clientX);
            }
        });

        document.addEventListener('touchend', () => {
            isDragging = false;
        });

        // Click anywhere on container to move slider
        container.addEventListener('click', (e) => {
            if (e.target !== sliderButton) {
                updateSlider(e.clientX);
            }
        });

        // Keyboard navigation for accessibility
        sliderButton.addEventListener('keydown', (e) => {
            const rect = container.getBoundingClientRect();
            const currentPercentage = parseFloat(sliderButton.getAttribute('aria-valuenow'));
            let newPercentage = currentPercentage;
            
            switch(e.key) {
                case 'ArrowLeft':
                case 'Left':
                    newPercentage = Math.max(0, currentPercentage - 1);
                    e.preventDefault();
                    break;
                case 'ArrowRight':
                case 'Right':
                    newPercentage = Math.min(100, currentPercentage + 1);
                    e.preventDefault();
                    break;
                case 'Home':
                    newPercentage = 0;
                    e.preventDefault();
                    break;
                case 'End':
                    newPercentage = 100;
                    e.preventDefault();
                    break;
                case 'PageDown':
                    newPercentage = Math.max(0, currentPercentage - 10);
                    e.preventDefault();
                    break;
                case 'PageUp':
                    newPercentage = Math.min(100, currentPercentage + 10);
                    e.preventDefault();
                    break;
            }
            
            if (newPercentage !== currentPercentage) {
                const newPosition = (newPercentage / 100) * rect.width + rect.left;
                updateSlider(newPosition);
            }
        });
    </script>
</body>
</html>

Breaking Down the Key Components

Let's examine how each piece of the code contributes to the final interaction.

The CSS Positioning System

The slider relies on absolute positioning within a relatively positioned container. The "after" image serves as the base layer, establishing the container's dimensions through its natural aspect ratio.

.comparison-container {
    position: relative;
    width: 100%;
    max-width: 800px;
    margin: 0 auto;
    overflow: hidden;
    border-radius: 10px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

The overflow: hidden declaration clips the overlay container, creating the reveal effect. Without this, the before image would extend beyond its designated area.

The Overlay Clipping Technique

The before image lives inside a div with variable width. As JavaScript adjusts this width, more or less of the before image becomes visible.

.img-overlay {
    position: absolute;
    top: 0;
    left: 0;
    width: 50%;
    height: 100%;
    overflow: hidden;
}

.img-overlay img {
    width: auto;
    height: auto;
    min-width: 100%;
    max-width: none;
    position: absolute;
    left: 0;
    top: 0;
}

The inner image uses min-width: 100% of the parent container (the full comparison container, not the overlay div). This ensures the before image always matches the after image's dimensions regardless of the clip position.

The Update Function

The core JavaScript function calculates the slider position and updates all visual elements accordingly.

function updateSlider(x) {
    const rect = container.getBoundingClientRect();
    let position = x - rect.left;
    
    // Constrain position within container
    position = Math.max(0, Math.min(position, rect.width));
    
    const percentage = (position / rect.width) * 100;
    
    overlay.style.width = percentage + '%';
    sliderButton.style.left = percentage + '%';
    sliderLine.style.left = percentage + '%';
    
    // Update ARIA attributes for screen readers
    const roundedPercentage = Math.round(percentage);
    sliderButton.setAttribute('aria-valuenow', roundedPercentage);
    sliderButton.setAttribute('aria-valuetext', `${roundedPercentage} percent - showing ${roundedPercentage}% before image and ${100 - roundedPercentage}% after image`);
}

The function receives an x-coordinate (from mouse, touch, or keyboard events), converts it to a percentage, and applies that percentage to the overlay width and slider position. The ARIA updates ensure screen readers announce the current state.

Keyboard Navigation Implementation

For accessibility compliance, the slider must work without a mouse. The keyboard handler responds to standard slider navigation keys as defined by WAI-ARIA authoring practices.

sliderButton.addEventListener('keydown', (e) => {
    const rect = container.getBoundingClientRect();
    const currentPercentage = parseFloat(sliderButton.getAttribute('aria-valuenow'));
    let newPercentage = currentPercentage;
    
    switch(e.key) {
        case 'ArrowLeft':
        case 'Left':
            newPercentage = Math.max(0, currentPercentage - 1);
            e.preventDefault();
            break;
        case 'ArrowRight':
        case 'Right':
            newPercentage = Math.min(100, currentPercentage + 1);
            e.preventDefault();
            break;
        // Additional keys omitted for brevity
    }
    
    if (newPercentage !== currentPercentage) {
        const newPosition = (newPercentage / 100) * rect.width + rect.left;
        updateSlider(newPosition);
    }
});

Arrow keys move in 1% increments for precision. Page Up and Page Down move 10% for faster traversal. Home and End jump to the extremes. The e.preventDefault() calls stop arrow keys from scrolling the page.

Customizing the Slider for Your Content

The code is designed for easy modification. Here are the most common customizations.

Replacing the Images

Update the src attributes on both image tags to point to your files. Also update the alt text to accurately describe your specific images.

<img src="your-after-image.jpg" alt="After: Description of the result state" id="afterImg">

For e-learning, descriptive alt text matters. Don't just say "before image" and "after image." Describe what each image actually shows so screen reader users understand the comparison.

Changing the Color Scheme

The slider button uses Bootstrap's primary blue (#0d6efd) by default. Modify the CSS to match your brand colors.

.slider-button {
    border: 3px solid #your-brand-color;
    color: #your-brand-color;
}

Consider accessibility when choosing colors. Maintain sufficient contrast between the button and the images behind it. White backgrounds with colored borders typically work well across varied image content.

Adjusting the Slider Size

The button dimensions and line width can be adjusted in the CSS. For mobile-first designs, you might want a larger touch target.

.slider-button {
    width: 80px;
    height: 80px;
    font-size: 32px;
}

.slider-line {
    width: 5px;
}

Apple's Human Interface Guidelines recommend touch targets of at least 44x44 points. The default 60x60 pixel button meets this standard, but larger is often better for accessibility.

Changing the Labels

Modify the label text to match your comparison context. For software training, you might use "Version 1.0" and "Version 2.0" or "Before Update" and "After Update."

<div class="label label-before" aria-hidden="true">Original</div>
<div class="label label-after" aria-hidden="true">Enhanced</div>

The aria-hidden="true" attribute prevents screen readers from announcing these visual labels separately. The slider's ARIA attributes already provide this information in a more meaningful format.

Accessibility Considerations

This slider implements WCAG 2.1 accessibility guidelines at the AA level. Understanding these features helps you maintain accessibility when customizing.

Semantic ARIA Roles

The slider button uses role="slider" to identify itself to assistive technology. Screen readers announce it as a slider control, setting user expectations for how it will behave.

<div class="slider-button" 
     role="slider" 
     aria-label="Image comparison slider"
     aria-valuemin="0" 
     aria-valuemax="100" 
     aria-valuenow="50"
     aria-valuetext="50 percent - showing half before and half after image"
     tabindex="0">⇔</div>

The aria-valuetext provides a human-readable description of the current state. Instead of just hearing "50," screen reader users hear "50 percent - showing half before and half after image."

Keyboard Operability

All functionality available via mouse is also available via keyboard. Users can tab to the slider and operate it entirely through key presses. This supports users who cannot use a mouse due to motor impairments.

Alternative Text for Images

The before and after images have alt text describing their content. If both images are purely decorative and the comparison itself is explained in surrounding text, you could use empty alt attributes (alt=""), but meaningful descriptions are usually preferable for educational content.

Troubleshooting Common Issues

Even simple interactions can encounter deployment issues. Here are solutions to frequent problems.

Images Not Loading

Verify that your image files are in the same folder as the HTML file (or update the paths accordingly). Check that file names match exactly, including capitalization. Web servers are often case-sensitive.

If hosting on a CDN or LMS, confirm that CORS headers allow the images to load. Some systems block cross-origin image requests.

Slider Not Responding to Touch

Ensure the viewport meta tag is present in the document head. Without it, mobile browsers may not properly register touch events.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Slider Position Drifts on Resize

The current implementation calculates positions at interaction time, so window resizing while dragging can cause minor drift. For most e-learning contexts, this is not an issue since users interact after the page loads.

If you need rock-solid resize handling, add a resize event listener that recalculates the slider position based on its stored percentage rather than pixel position.

Images Have Different Dimensions

The slider works best when both images have identical dimensions. If your images differ, the smaller one will leave gaps. Resize your images to match before implementing the slider.

For responsive images, both should have the same aspect ratio even if their pixel dimensions vary. The CSS scales them to match the container.

Taking It Further

This basic implementation provides a solid foundation. Consider these enhancements for advanced use cases.

Adding Multiple Sliders

To include multiple comparison sliders on one page, assign unique IDs to each container and its children. Then initialize separate JavaScript instances for each slider, passing the container reference.

Vertical Slider Option

The same technique works for vertical comparisons. Rotate the positioning logic to use height instead of width, top instead of left, and change the cursor to ns-resize.

Integration with Storyline Variables

For Storyline web objects, you can pass the current slider position back to Storyline using the parent window's API. This enables triggering layers or advancing slides based on learner interaction.

// Send value to Storyline
const player = parent.GetPlayer();
player.SetVar("SliderPosition", roundedPercentage);

This requires setting up corresponding variables in your Storyline project and handling the web object's JavaScript communication properly.

Conclusion

An image comparison slider adds visual impact and interactivity to your e-learning content. The technique works across platforms, requires no external dependencies, and meets accessibility standards out of the box.

Start with this code as your foundation, customize the styling to match your brand, and swap in your own before-and-after images. Your learners will appreciate the engaging, hands-on way to explore visual differences in your training content.

Download the complete code files and start building your own image comparison slider today.

Nathan Stoker

I build custom eLearning in Storyline, Rise and JavaScript, and I make the free tools and templates on this site. Need an interaction like this in your course? Let's talk.

Work with me · Browse templates

Related posts