Flickity - Documentation

Getting Started

Installation

Flickity can be installed via npm, yarn, or by including a <script> tag.

npm:

npm install flickity

yarn:

yarn add flickity

<script> tag: Download the Flickity JavaScript and CSS files from the Flickity website and include them in your HTML file. For example:

<link rel="stylesheet" href="flickity.css">
<script src="flickity.pkgd.min.js"></script>

Remember to replace "flickity.css" and "flickity.pkgd.min.js" with the actual paths to your downloaded files. Using the packaged flickity.pkgd.min.js file includes all the necessary dependencies.

Basic Setup

Once installed, you need to include the Flickity CSS and JavaScript in your project. This is done as described in the Installation section above. Then you’ll need to create a container element for your carousel and add the necessary classes and attributes.

The basic HTML structure looks like this:

<div class="carousel" data-flickity='{ "freeScroll": true }'>
  <div class="carousel-cell"></div>
  <div class="carousel-cell"></div>
  <div class="carousel-cell"></div>
</div>

The data-flickity attribute is a JSON string containing Flickity options. In this example, freeScroll: true enables free scrolling. You can customize many aspects of Flickity using these options (see the Flickity documentation for a complete list).

Let’s create a simple carousel with three images. First, include the necessary CSS and JavaScript as in the Installation section. Then, add the following HTML:

<div class="carousel" data-flickity='{ "wrapAround": true }'>
  <div class="carousel-cell"><img src="image1.jpg" alt="Image 1"></div>
  <div class="carousel-cell"><img src="image2.jpg" alt="Image 2"></div>
  <div class="carousel-cell"><img src="image3.jpg" alt="Image 3"></div>
</div>

This code creates a carousel that wraps around (meaning you can seamlessly loop from the last to the first image and vice-versa), thanks to "wrapAround": true in the data-flickity attribute. Replace "image1.jpg", "image2.jpg", and "image3.jpg" with the actual paths to your images. Remember to adjust the styling as needed to fit your design. You can add more cells to the carousel to display more images. For further customization, refer to the Flickity documentation’s extensive options and API details.

Options and Configuration

Configuring Cell Selectors

By default, Flickity selects all direct children of the carousel element as cells. However, you can customize this using the cellSelector option. This is useful if your carousel items aren’t direct children, or if you need more specific selection criteria.

For example, if your carousel cells are within <li> elements:

<div class="carousel" data-flickity='{ "cellSelector": "li" }'>
  <li><img src="image1.jpg" alt="Image 1"></li>
  <li><img src="image2.jpg" alt="Image 2"></li>
  <li><img src="image3.jpg" alt="Image 3"></li>
</div>

In this case, cellSelector: "li" tells Flickity to select all <li> elements within the .carousel as cells. You can use any valid CSS selector here.

Options Reference

Flickity offers a wide range of options to customize its behavior. These options can be set using the data-flickity attribute or by passing an options object to the Flickity constructor. Here’s a summary of some key options:

This is not an exhaustive list. Refer to the complete Flickity documentation for all available options and their descriptions.

Responsive Settings

Flickity can adapt to different screen sizes using responsive settings. You can achieve this using either media queries and the data-flickity attribute or by directly updating options using JavaScript.

Using Media Queries: You can apply different data-flickity attributes to your carousel element based on screen size using CSS media queries. For example:

@media (min-width: 768px) {
  .carousel {
    data-flickity='{ "cellAlign": "left" }';
  }
}

Updating Options with JavaScript: You can listen to window resize events and update Flickity options accordingly. This is more flexible for complex responsive behaviour. For example:

const flkty = new Flickity( '.carousel' );

window.addEventListener('resize', function() {
  if (window.innerWidth > 768) {
    flkty.update({ cellAlign: 'left' });
  } else {
    flkty.update({ cellAlign: 'center' });
  }
});

Using Data Attributes

Data attributes provide a convenient way to configure Flickity options directly in your HTML. You place the options within a JSON object in the data-flickity attribute of your carousel container. For example:

<div class="carousel" data-flickity='{ "wrapAround": true, "autoPlay": 3000 }'>
  <!-- Carousel cells -->
</div>

This sets wrapAround to true and enables auto-play with a 3000ms interval. This approach is concise for simple configurations. For more complex scenarios or dynamic changes, using JavaScript to instantiate and configure Flickity is recommended.

Methods

Flickity provides several methods to interact with and control the carousel after initialization. These methods are called on the Flickity instance.

.select(index, isInstant)

Selects a specific cell by its index.

const flkty = new Flickity( '.carousel' );
flkty.select(2); // Selects the third cell.
flkty.select(0, true); // Selects the first cell instantly.

.previous()

Selects the previous cell.

const flkty = new Flickity( '.carousel' );
flkty.previous();

.next()

Selects the next cell.

const flkty = new Flickity( '.carousel' );
flkty.next();

.resize()

Updates the Flickity layout after changes to the carousel’s content or dimensions. This is crucial after dynamically adding or removing cells, or resizing the window.

const flkty = new Flickity( '.carousel' );
flkty.resize();

.destroy()

Completely removes Flickity from the element, restoring its original state. This is useful for cleanup when the carousel is no longer needed.

const flkty = new Flickity( '.carousel' );
flkty.destroy();

.reloadCells()

Re-selects the cells from the DOM. Use this if the content of the cells has changed significantly (e.g., the number of cells has changed, or their dimensions have altered unexpectedly).

const flkty = new Flickity( '.carousel' );
flkty.reloadCells();

.getCellElements()

Returns an array of the DOM elements representing the cells.

const flkty = new Flickity( '.carousel' );
const cells = flkty.getCellElements();
console.log(cells); // Array of cell DOM elements

.getCurrentCell()

Returns the currently selected cell’s element.

const flkty = new Flickity( '.carousel' );
const currentCell = flkty.getCurrentCell();
console.log(currentCell); // DOM element of the current cell

.getCells()

Returns an array of Flickity Cell instances. Each Cell instance contains more detailed information about each cell than just the DOM element (e.g., its index, element, and position).

const flkty = new Flickity( '.carousel' );
const cells = flkty.getCells();
console.log(cells); // Array of Flickity Cell instances
console.log(cells[0].element); // DOM element of the first cell
console.log(cells[0].index); // Index of the first cell

Events

Flickity triggers various events throughout its lifecycle, allowing you to respond to changes in the carousel’s state. These events can be used to enhance the user experience or integrate Flickity with other JavaScript components.

Overview of Flickity Events

Flickity events are dispatched on the Flickity instance. They are typically handled using the addEventListener method. Events are categorized into several types:

Event List and Details

Here’s a list of key Flickity events and their descriptions:

Example Event Handling

This example shows how to handle the select and resize events:

const flkty = new Flickity( '.carousel' );

flkty.on( 'select', function( event ) {
  console.log( `Selected cell index: ${event.selectedIndex}` );
  // Add your code to handle the selection event here, e.g., update UI elements
});

flkty.on( 'resize', function() {
  console.log( 'Carousel resized' );
  // Perform actions needed after the carousel resizes, like adjusting other elements
});


//Alternatively, using addEventListener

flkty.addEventListener('select', function(event) {
    console.log(`Selected cell index: ${event.selectedIndex}`);
});

//Removing Event Listeners
flkty.removeEventListener('select', function(event) {
    //Do something
});

Remember to replace '.carousel' with the selector for your Flickity carousel element. You can handle other events in a similar manner, using the appropriate event name. The on() method is a shorthand for addEventListener(). removeEventListener() is used to remove event listeners. Consult the Flickity documentation for details on the event objects and properties for each event.

Advanced Usage

This section covers more complex scenarios and techniques for working with Flickity.

Creating Custom Cell Elements

Flickity offers great flexibility in how you structure your carousel cells. While the basic example uses <div> elements, you can use any HTML element as a cell. This enables you to create complex and visually rich carousels.

For example, you could create cells with custom layouts using flexbox or grid:

<div class="carousel" data-flickity>
  <div class="carousel-cell">
    <div class="cell-image"><img src="image1.jpg" alt="Image 1"></div>
    <div class="cell-caption">Image Caption 1</div>
  </div>
  <div class="carousel-cell">
    <div class="cell-image"><img src="image2.jpg" alt="Image 2"></div>
    <div class="cell-caption">Image Caption 2</div>
  </div>
  <!-- More cells -->
</div>

Remember to style the .carousel-cell, .cell-image, and .cell-caption classes appropriately to achieve the desired layout and appearance.

Working with Multiple Flickity Instances

You can easily have multiple Flickity carousels on a single page. Simply create separate containers for each carousel and initialize Flickity on each:

const carousel1 = new Flickity( '.carousel-1' );
const carousel2 = new Flickity( '.carousel-2', {
  cellAlign: 'left' // Different options for each carousel
});

Each instance will have its own properties and methods, allowing for independent control over each carousel.

Implementing Drag and Swiping

Flickity handles dragging and swiping by default, but you can customize the behavior using options like draggable, friction, and event listeners (dragStart, dragMove, dragEnd). You could, for example, add visual feedback during dragging or disable dragging altogether:

const flkty = new Flickity('.carousel', {
  draggable: true, //Enable/disable dragging
  friction: 0.5 // Adjust dragging friction
});

flkty.on( 'dragStart', function() {
  // Add visual feedback, e.g., highlight dragged cell
});

flkty.on('dragMove', function(event) {
    //Update a progress bar based on current drag position (event.x, event.y)
});

Accessibility Considerations

To ensure your Flickity carousel is accessible, utilize ARIA attributes. Flickity enables ARIA attributes by default (accessibility: true). Additionally:

Integrating with Other Libraries

Flickity can be integrated with other JavaScript libraries. For example, you could combine it with libraries for lazy-loading images, lightboxes, or parallax effects. The key is to ensure the other library’s events and methods don’t conflict with Flickity’s. This might involve careful timing of events or using techniques like event delegation. For instance, consider using Flickity’s ready event to initialize a lazy-loading library after Flickity is fully setup.

Remember to thoroughly test your integration to ensure everything works as expected.

Troubleshooting

This section helps you diagnose and resolve common problems encountered when using Flickity.

Common Issues and Solutions

Debugging Tips

Performance Optimization

API Reference

This section provides a detailed reference for the Flickity API.

Flickity Class

The Flickity class is the main constructor for creating a Flickity carousel.

Constructor:

new Flickity( element, options )

Flickity Instance Methods

After creating a Flickity instance, you can use the following methods to interact with it:

Event Handling Methods:

The on(), once(), and off() methods are used to manage events. The eventName is a string representing the event name (e.g., select, resize, change). The listener is a callback function that will be executed when the event is triggered. For example:

flkty.on( 'select', function( event ) {
  console.log( 'Selected cell:', event.selectedIndex );
});

Flickity Options

These options can be passed to the Flickity constructor or set using the data-flickity attribute:

This is not an exhaustive list. Refer to the complete Flickity documentation for all available options and their descriptions. The default values are shown above, but remember that the latest documentation might have updates.