Skip to main content
March 23, 2026Dan Rodney/9 min read

Using a JavaScript Library: Slideshow/Carousel

Master interactive carousels with JavaScript library integration

Core JavaScript Slideshow Skills

HTML Structure Setup

Learn to implement specific markup patterns required by JavaScript libraries. Understanding proper class naming and element nesting is crucial for functionality.

Library Integration

Master linking external CSS and JavaScript files in the correct order. Proper file linking ensures all dependencies load before initialization.

Configuration Options

Customize slideshow behavior through JavaScript objects. Options control display count, spacing, navigation, and responsive breakpoints.

Topics Covered in This JavaScript Tutorial:

Setting up the HTML Content, Linking to the Provided Files, Initializing the Script, Customizing the Script Using Provided Options, Tweaking Some CSS

Exercise Preview

preview carousel

Splide Library Focus

This tutorial uses Splide, a lightweight and flexible slider library. The principles learned apply to most JavaScript carousel libraries with similar initialization patterns.

Exercise Overview

In this exercise, you'll master the implementation of Splide, a powerful and lightweight carousel library that has become an industry standard for creating responsive slideshows and image galleries. Carousels remain one of the most effective UI patterns for showcasing multiple pieces of content in a confined space—whether you're building an e-commerce product gallery, a news ticker, or a portfolio showcase.

What sets Splide apart from other carousel solutions is its modern architecture, excellent mobile support, and extensive customization options. Unlike older libraries that rely heavily on jQuery, Splide is built with vanilla JavaScript, making it faster and more compatible with modern development workflows. You'll learn not just how to implement it, but how to configure it professionally for real-world applications.

Setting up the HTML Content

Professional JavaScript libraries follow semantic HTML conventions, requiring specific markup structures that their CSS and JavaScript can reliably target. This isn't arbitrary—it ensures consistent behavior across different browsers and devices while maintaining accessibility standards. Splide's documentation at splidejs.com provides comprehensive examples, but understanding the underlying structure is crucial for customization.

Rather than directing you to external documentation that may change, we've curated the essential code snippets you need. This approach ensures you'll have working examples regardless of future updates to the library's website.

  1. Navigate to the Carousel folder located in Desktop > Class Files > JavaScript Class. Open this folder in your code editor—modern editors like Visual Studio Code provide excellent project-level file management that will streamline your workflow.

  2. From the snippets folder, open splide-tags.html.

    Examine the class naming convention—each class is prefixed with "splide" using BEM (Block Element Modifier) methodology. This namespacing prevents style conflicts with your existing CSS and follows modern front-end architecture principles. The double underscore syntax (splide__slide) indicates a child element, while any double dashes would indicate modifiers.

    We've already integrated this structure into our working HTML file and enhanced it with realistic content to demonstrate professional implementation patterns.

  3. Open index.html from the Carousel folder.
  4. Locate line 26, just below <div id="more-news">. You'll see we've implemented the same semantic structure with two key enhancements:

    • Meaningful heading text that provides proper context for screen readers and SEO.
    • Each slide contains a complete link structure with images and headings—this follows accessibility best practices by ensuring keyboard navigation works correctly. (Note: The links are placeholders for this exercise.)
  5. Preview index.html in Chrome, which we'll use for its superior DevTools.

    • Scroll to the More News section.
    • Notice how the content appears as a standard vertical list—this is the unstyled, accessible fallback that ensures your content remains functional even if JavaScript fails to load. This progressive enhancement approach is a hallmark of professional web development.
  6. Keep the browser tab open—we'll be monitoring changes in real-time as we enhance the functionality.

HTML Structure Implementation

1

Copy Base Markup

Use the provided splide-tags.html file to get the correct HTML structure with proper class names

2

Add Content

Insert your images and text within the splide__slide li tags while maintaining the required structure

3

Verify Structure

Ensure all splide-specific classes are present as the JavaScript targets these for functionality

Linking to the Provided Files

Modern JavaScript libraries typically consist of both CSS and JavaScript components. The CSS handles the visual presentation and animations, while the JavaScript manages the interactive behavior. Loading these in the correct order is crucial for proper functionality.

  1. Return to your code editor to begin linking the required assets.
  2. Splide's CSS contains optimized styles for cross-browser compatibility and smooth animations. Add the stylesheet link after normalize.css:

    <link rel="stylesheet" href="css/normalize.css">
       <link rel="stylesheet" href="js/vendor/splide-4.0.0/css/splide.min.css">
       <link rel="stylesheet" href="css/main.css">
    </head>

    NOTE: While we've included Splide files locally for this exercise, production projects should reference the latest version from splidejs.com or use a CDN for better caching and performance. Always check for security updates and new features in your dependency management workflow.

  3. Save and reload the page in Chrome.

    In the More News section, you'll notice the content appears hidden—this is expected behavior. Splide's CSS prepares the layout for the carousel functionality, hiding slides that aren't currently active. The content will reappear once we initialize the JavaScript component.

  4. Now add the JavaScript library. Script loading order matters—Splide must load before our custom initialization code. Add this near the closing body tag:

    <script src="js/vendor/splide-4.0.0/js/splide.min.js"></script>
    <script src="js/main.js"></script>
    </body>

File Linking Checklist

0/3
Content Visibility

After linking the Splide CSS, content may appear hidden. This is normal behavior until the JavaScript initializes the carousel functionality.

Initializing the Slider/Carousel

Initialization is where the magic happens—this is where we transform static HTML into an interactive carousel. Modern JavaScript libraries use constructor patterns and event-driven architectures to ensure reliable performance across different devices and browsers.

  1. From the snippets folder, open splide-initialize.js to examine the initialization pattern.
  2. Copy all the code—this represents the minimal setup required for a functioning carousel.
  3. Open main.js from the js folder.
  4. Paste the initialization code:

    document.addEventListener( 'DOMContentLoaded', function() {
       var splide = new Splide( '.splide' );
       splide.mount();
     } );

    NOTE: This code uses var for variable declaration, which you'll encounter frequently in JavaScript libraries and legacy codebases. While let and const offer improved scoping behavior in modern JavaScript, var provides broader browser compatibility. In this context, all three approaches work identically, but understanding these variations is essential for working with diverse codebases.

  5. Save and reload the page in Chrome.

    Your carousel is now functional! Test these professional-grade features:

    • Touch/swipe gestures work seamlessly on both mobile and desktop—Splide includes pointer event handling that works across all modern input methods.
    • Responsive behavior adapts to window resizing automatically, maintaining optimal display proportions.
    • Keyboard navigation support ensures accessibility compliance for users who navigate without a mouse.
document.addEventListener('DOMContentLoaded', function() { var splide = new Splide('.splide'); splide.mount(); });
Basic Splide initialization code that waits for DOM to load before creating the carousel instance

Initialization Features

Touch/Drag Support

Works on both mobile devices and desktops. Users can drag directly on carousel content to navigate between slides.

Responsive Display

By default shows one item at a time. Automatically adapts to different screen sizes with proper configuration.

Customizing the Script Using Provided Options

Professional carousel implementation requires fine-tuning for your specific use case. Splide offers over 50 configuration options, allowing you to control everything from animation timing to responsive breakpoints. This flexibility is what separates enterprise-ready libraries from basic plugins.

The complete options reference at splidejs.com/guides/options demonstrates the library's depth, but we'll focus on the most impactful settings for professional implementations.

  1. Switch back to main.js in your code editor.
  2. Transform the basic initialization into a configurable implementation by adding an options object:

    var splide = new Splide( '.splide' , {} );
  3. Configure the carousel to display multiple items simultaneously—a common requirement for product galleries and news feeds:

    var splide = new Splide( '.splide', {
       perPage: 3
    } );
  4. Save and reload the page in Chrome.

    The carousel now displays three items at once, creating a more efficient use of screen real estate and allowing users to see more content context before deciding to advance.

  5. Visual spacing between carousel items prevents content from appearing cramped and improves readability. Add the gap configuration:
  6. Enhance the visual design with proper spacing:

    var splide = new Splide( '.splide', {
       perPage: 3, 
       gap: 20
    } );
  7. Save and reload the page in Chrome. Observe the improvements:

    • Clean spacing between items creates a more polished, professional appearance.
    • Navigate to the end using the arrow controls—currently, the carousel stops abruptly, creating a jarring user experience.
  8. Return to main.js to implement continuous navigation.
  9. Enable infinite scrolling behavior that's expected in modern carousel implementations:

    var splide = new Splide( '.splide', {
       perPage: 3, 
       gap: 20, 
       rewind: true
    } );
  10. Save and reload the page in Chrome.

    Test the navigation—the carousel now provides seamless looping, creating a more intuitive and engaging user experience that keeps visitors engaged with your content.

Configuration Options Applied

Items Per Page
3
Gap (pixels)
20
Rewind Enabled
1
Option Documentation

Complete Splide options are available at splidejs.com/guides/options. Each option is well-documented with examples and default values.

Moving the Prev & Next Arrows Outside the Content

Professional carousel implementations require careful attention to visual hierarchy and user interface clarity. When navigation controls overlap content, it can create accessibility issues and reduce the impact of your visual elements. Strategic padding solves this while maintaining responsive design principles.

  1. Switch back to your code editor to implement the visual refinements.
  2. From the css folder, open main.css.
  3. Add professional spacing that accommodates the navigation controls:

    .splide {
       padding: 0 55px 35px;
    }
    @media (min-width: 1100px) {

    NOTE: This CSS shorthand follows the standard pattern: top, horizontal (left/right), bottom. The 55px horizontal padding provides clearance for arrow buttons, while 35px bottom padding accommodates pagination dots.

  4. Save and reload the page in Chrome. Notice the professional improvements:

    • Navigation controls no longer obscure your content, improving both aesthetics and usability.
    • However, displaying three items on narrow screens creates cramped, unusable layouts—this is where responsive configuration becomes essential.

CSS Padding Solution

1

Target Splide Container

Use the .splide class selector to add padding without affecting other page elements

2

Apply Strategic Padding

Use padding: 0 55px 35px to create space for arrows on sides and pagination dots below

3

Test Control Placement

Verify navigation controls no longer overlap with carousel content

Controlling How Many Items Are Visible at Various Screen Sizes

Responsive carousel behavior is non-negotiable in modern web development. With mobile traffic consistently exceeding desktop usage across most industries, your carousel must adapt intelligently to different viewport sizes. Splide's breakpoint system provides granular control over this behavior.

  1. Return to main.js in your code editor.

  2. Implement responsive breakpoints that ensure optimal viewing across all devices:

    var splide = new Splide( '.splide', {
       perPage: 3, 
       gap: 20, 
       rewind: true, 
       breakpoints: {
          850: {
             perPage: 2
          }, 
          600: {
             perPage: 1
          }
       }
    } );
  3. Save and reload the page in Chrome.

    Test the responsive behavior by resizing your browser window. The carousel intelligently adapts: single items on mobile devices, two items on tablets, and three items on desktop displays. This creates an optimal viewing experience regardless of the user's device.

    NOTE: When implementing responsive carousels in production, ensure your images are optimized for the largest possible display size. This allows for clean downscaling without pixelation—upscaling low-resolution images creates poor user experiences and reflects poorly on your brand.

Responsive Breakpoint Strategy

Small Screens (0-599px)
1
Medium Screens (600-849px)
2
Large Screens (850px+)
3
Image Size Considerations

Always size images for the widest possible display to avoid pixelation when scaling. Images should only scale down, never up.

Optional Bonus: Lazy Loading Content

Performance optimization is crucial for modern web applications. Images typically account for 60-70% of a webpage's total size, and carousel images compound this issue since users may never view slides beyond the first few. Lazy loading is a performance optimization technique that defers image loading until needed, dramatically improving initial page load times—especially important for mobile users on slower connections.

  1. Switch to main.js in your code editor.
  2. Enable Splide's built-in lazy loading functionality:

    var splide = new Splide( '.splide', {
       lazyLoad: 'nearby', 
       perPage: 3, 
  3. Save the file.

    The 'nearby' setting intelligently preloads adjacent slides for smooth navigation while avoiding unnecessary downloads. However, we need to modify our HTML to prevent the browser from loading images immediately.

  4. Switch to index.html in your code editor.

  5. Transform standard img tags into lazy-loaded elements by changing the src attribute to data-splide-lazy for every image within the carousel structure:

    <img data-splide-lazy="img/duck.jpg" ALT="Ducks. One has a raised leg.">

    TIP: Modern code editors provide efficient multi-cursor editing. In Visual Studio Code, select the first img src= occurrence, then use Cmd–D (Mac) or Ctrl–D (Windows) to select subsequent matches. This allows simultaneous editing across multiple instances—a essential workflow optimization for professional development.

  6. Save and reload the page in Chrome.

  7. Open Chrome DevTools using Cmd–Opt–J (Mac) or Ctrl–Shift–J (Windows).
  8. Navigate to the Network tab. If it's not visible, click the >> button and select Network from the dropdown menu.
  9. Reload the page using Cmd–R (Mac) or Ctrl–R (Windows) to monitor the loading behavior.
  10. Examine the Initiator column for the loaded files:

    Carousel images show setAttribute as their initiator, confirming they were loaded by JavaScript after the initial page load. In contrast, the logo shows index.html, indicating standard HTML loading. This demonstrates that lazy loading is functioning correctly, improving your site's performance metrics and user experience.

Lazy Loading Benefits

Pros
Faster initial page load times
Reduced bandwidth usage on mobile
Better performance on slow connections
Images load as needed during navigation
Cons
Requires changing all img src attributes
Slight delay when viewing new slides
More complex implementation

Lazy Loading Implementation

1

Enable Lazy Loading Option

Add lazyLoad: 'nearby' to the Splide configuration object

2

Modify Image Attributes

Change all img src attributes to data-splide-lazy to prevent immediate loading

3

Verify in DevTools

Check Network tab to confirm images load via JavaScript (setAttribute) rather than HTML

Key Takeaways

1JavaScript libraries like Splide require specific HTML structure with designated class names to function properly
2File linking order is crucial - CSS and JavaScript dependencies must load before custom code initialization
3DOM ready events ensure JavaScript runs only after HTML elements are fully loaded and accessible
4Configuration objects allow extensive customization of carousel behavior including display count, spacing, and navigation
5Responsive breakpoints enable different carousel settings at various screen widths for optimal mobile experience
6CSS padding can solve layout issues when JavaScript options are insufficient for visual adjustments
7Lazy loading improves page performance by deferring image downloads until needed during carousel navigation
8DevTools Network tab helps verify proper lazy loading implementation by showing JavaScript-initiated image requests

RELATED ARTICLES