Simple, framework-agnostic carousel library written in vanilla JavaScript.



Setup
Start by preparing your HTML.
<div id="slider">
<div><h2>Hello Slide 1</h2></div>
<div><h2>Hello Slide 2</h2></div>
<div><h2>No hello to you slide 3</h2></div>
</div>
Initialize the slider. Additionally, you can include options to modify the behavior of the carousel.
import Slider from './slider.js'
const slider = new Slider('#slider', {
width: 600,
height: 400
})
And there you go. The slider also exposes control methods, which allow you to dynamically update the slider with code, not just user input.
// Sets the slide at provided index as the active one
slider.set(index)
// Slide to the previous/next slide
slider.prev()
slider.next()
// Add or remove a slide at the provided index
slider.add(el, index) // el: string | HTMLElement
slider.remove(index)
You can also integrate it with frameworks like Vue or React if you need reactivity by using event listeners.
For example, register a listener for when a slide is changed:
// Fired whenever slide is changed
slider.onSlideChange((event, { fromIndex, toIndex }) => {})
// Changed from navigation (prev/next) buttons
slider.onSlideChangeFromButton()
// Changed when dragging with mouse
slider.onSlideChangeFromDrag()
// Changed when clicking the small dot at the bottom
slider.onSlideChangeFromDot()
The Buzzcut API
So what makes this library interesting? The buzzcut. It gives you a simpler way to initialize a slider, but offers a bit less control.
With this approach, you don’t have to explicitly create a slider instance for each slider. You can also use imported methods, but you have to pass the your_slider_id before other arguments.
Let’s check out an example:
<div slider="my-slider" slider-width="728" slider-height="480">
<div><h2>Hello Slide 1</h2></div>
<div><h2>Hello Slide 2</h2></div>
</div>
After your DOM is loaded, make sure you import the register() method and run it. All it does is collect all the sliders you’ve prepared and initialize them.
import { register } from './slider.js'
// Sliders will be registered when DOM is loaded so it does not matter where you call this function
register()
import { next, prev } from './slider.js'
// Will go to the next slide in the 'my-slider' element
next('my-slider')
next('my-other-slider')
// If you call this method without id,
// it will be applied to the first slider it finds in the dom or
// you'll get a warning that the slider was not found
next()
Footnote
This project was another one of the ‘can I do it myself?’ type of projects. While it is mainly created to be used within my personal projects, if you’ve tried it and have an issue or a suggestion, please submit it to the repo! I appreciate any sort of feedback :)
