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

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.
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.
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.
- Open index.html from the Carousel folder.
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.)
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.
Keep the browser tab open—we'll be monitoring changes in real-time as we enhance the functionality.
HTML Structure Implementation
Copy Base Markup
Use the provided splide-tags.html file to get the correct HTML structure with proper class names
Add Content
Insert your images and text within the splide__slide li tags while maintaining the required structure
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.
- Return to your code editor to begin linking the required assets.
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.
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.
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
CSS order matters for proper styling cascade
Dependencies must load before your custom code
Broken links will prevent the carousel from functioning
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.
- From the snippets folder, open splide-initialize.js to examine the initialization pattern.
- Copy all the code—this represents the minimal setup required for a functioning carousel.
- Open main.js from the js folder.
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.
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(); });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.
- Switch back to main.js in your code editor.
Transform the basic initialization into a configurable implementation by adding an options object:
var splide = new Splide( '.splide' , {} );Configure the carousel to display multiple items simultaneously—a common requirement for product galleries and news feeds:
var splide = new Splide( '.splide', { perPage: 3 } );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.
- Visual spacing between carousel items prevents content from appearing cramped and improves readability. Add the gap configuration:
Enhance the visual design with proper spacing:
var splide = new Splide( '.splide', { perPage: 3, gap: 20 } );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.
- Return to main.js to implement continuous navigation.
Enable infinite scrolling behavior that's expected in modern carousel implementations:
var splide = new Splide( '.splide', { perPage: 3, gap: 20, rewind: true } );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
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.
- Switch back to your code editor to implement the visual refinements.
- From the css folder, open main.css.
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.
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
Target Splide Container
Use the .splide class selector to add padding without affecting other page elements
Apply Strategic Padding
Use padding: 0 55px 35px to create space for arrows on sides and pagination dots below
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.
Return to main.js in your code editor.
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 } } } );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
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.
- Switch to main.js in your code editor.
Enable Splide's built-in lazy loading functionality:
var splide = new Splide( '.splide', { lazyLoad: 'nearby', perPage: 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.
Switch to index.html in your code editor.
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.
Save and reload the page in Chrome.
- Open Chrome DevTools using Cmd–Opt–J (Mac) or Ctrl–Shift–J (Windows).
- Navigate to the Network tab. If it's not visible, click the
>>button and select Network from the dropdown menu. - Reload the page using Cmd–R (Mac) or Ctrl–R (Windows) to monitor the loading behavior.
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
Lazy Loading Implementation
Enable Lazy Loading Option
Add lazyLoad: 'nearby' to the Splide configuration object
Modify Image Attributes
Change all img src attributes to data-splide-lazy to prevent immediate loading
Verify in DevTools
Check Network tab to confirm images load via JavaScript (setAttribute) rather than HTML