Swipe JS - Documentation

What is SwipeJS?

SwipeJS is a lightweight, dependency-free JavaScript library designed to create touch-friendly image carousels and sliders. It provides a simple and intuitive API for implementing swipe gestures on various devices, allowing users to navigate through a series of images or content elements with ease. SwipeJS focuses on ease of use and minimal code, making it ideal for quickly adding swipe functionality to your web projects.

Why use SwipeJS?

Setting up SwipeJS

SwipeJS is typically included via a <script> tag in your HTML file. You can download the library from [Insert Download Link Here] and save it in your project’s js directory (or a similar location). Then, include it in your HTML like this:

<script src="js/swipe.js"></script>

Alternatively, you can use a CDN (Content Delivery Network) if one is available. (Insert CDN link if applicable, otherwise remove this sentence). Remember to include this script after your HTML elements that will be controlled by SwipeJS.

Basic Example

This example shows a simple image carousel using SwipeJS. First, create your HTML structure:

<div id="mySwipe" class="swipe">
  <div class="swipe-wrap">
    <div><img src="image1.jpg" alt="Image 1"></div>
    <div><img src="image2.jpg" alt="Image 2"></div>
    <div><img src="image3.jpg" alt="Image 3"></div>
  </div>
</div>

Next, initialize SwipeJS in your JavaScript file (or within a <script> tag at the end of your body):

var mySwipe = new Swipe(document.getElementById('mySwipe'), {
  startSlide: 0, // optional, starting slide (0-indexed)
  speed: 400,     // optional, transition speed in milliseconds (default is 300)
  auto: 3000,    //optional, autoplay timer in milliseconds (default is 0 - off)
  continuous: true //optional, continuous swipe (default is true)
});

This code selects the element with the ID “mySwipe” and initializes a Swipe instance. Replace "image1.jpg", "image2.jpg", and "image3.jpg" with the actual paths to your images. The options are optional and allow customization of the slider’s behaviour. Remember that the CSS classes (swipe, swipe-wrap) are crucial for SwipeJS to function correctly, so don’t alter them unless explicitly stated in the advanced usage section of the documentation.

Core Concepts

Swipe Gestures

SwipeJS primarily responds to swipe gestures. A swipe is defined as a quick, continuous movement of a finger across the touchscreen (or a similar action using a mouse on desktop). SwipeJS detects both horizontal and vertical swipes, although it’s most commonly used for horizontal swiping through a series of elements (like images in a carousel). The direction and speed of the swipe determine the action taken (e.g., moving to the next or previous slide). SwipeJS automatically handles the detection and interpretation of these gestures, providing a smooth and intuitive user experience.

Event Handling

While SwipeJS automatically handles the core swipe actions, it also allows you to respond to specific events within your own JavaScript code. This allows for extending the functionality of the slider beyond the basic swipe navigation. Event handling is primarily achieved through callbacks, which are functions that are executed when certain events occur. These events are detailed in the “Callbacks and Events” section below. Generally, these events are triggered by the user interaction (like swiping, tapping, or reaching the beginning/end of the slide deck) or by automated actions (like auto-sliding).

Configuration Options

SwipeJS provides several configuration options to customize the slider’s behavior. These options are passed as an object to the Swipe constructor. Some key options include:

These options allow developers to fine-tune the slider to fit their specific needs and design. More options might be available depending on the version of SwipeJS used; refer to the library’s documentation for a complete list.

Callbacks and Events

SwipeJS provides several callbacks that allow you to execute custom code at specific points during the slider’s operation. These are passed as options to the Swipe constructor. The most common callback is:

Example:

var mySwipe = new Swipe(document.getElementById('mySwipe'), {
  callback: function(index, element) {
    console.log("Current slide index: " + index);
    // Add your custom code here, e.g., update a progress bar
  }
});

Other events might be available depending on the library’s version; always consult the updated documentation for the most accurate and complete list of callbacks and events. Note that the exact names and arguments of callbacks might vary slightly depending on the SwipeJS version. Always refer to the library’s documentation for the latest information.

API Reference

SwipeJS Object

The core of SwipeJS is the Swipe object. This object is created by calling the Swipe() constructor, passing the element to be swiped and an optional configuration object as arguments. The constructor returns a Swipe object which provides access to methods and properties for controlling the slider’s behavior. Once created, the Swipe object manages the swipe gestures and handles the transitions between slides within the target element.

var mySwipe = new Swipe(element, options);

Where:

Methods

The Swipe object provides the following methods:

Events

While SwipeJS handles the core swipe actions internally, it doesn’t directly expose custom events in the typical addEventListener sense. Instead, event-driven behavior is primarily achieved through the callback function provided in the configuration options. This function is triggered after each slide transition and provides the index of the current slide, allowing for custom actions based on the slide change.

(Note: Depending on the SwipeJS version, additional event mechanisms might exist, often documented within the library’s source code comments or within a separate dedicated events section in an up-to-date documentation).

Properties

The Swipe object doesn’t expose public properties directly accessible through the object’s attributes (e.g., mySwipe.currentSlide). The current slide index can be accessed using the getPos() method. Direct access to internal properties is not recommended, as it might break with future updates of the library. The internal structure of the Swipe object is for internal use and should not be relied upon for external interactions. The public API (methods and the callback) should be sufficient for all interaction needs.

Advanced Usage

Customizing Swipe Behavior

Beyond the basic configuration options, you can further customize SwipeJS behavior through CSS and JavaScript. CSS allows you to style the slider’s appearance, while JavaScript offers more control over the swipe actions and transitions.

CSS Customization: You can style the slider’s appearance using standard CSS. Target the classes provided by SwipeJS (e.g., .swipe, .swipe-wrap, .swipe-wrap > div) to modify the look and feel of the slider, individual slides, and navigation elements (if any are added). Remember that modifying the core structural classes should be done with caution to ensure compatibility with the library.

JavaScript Customization: You can extend the functionality by using the callback function to perform actions after each slide transition, for instance: changing other elements on the page, showing/hiding additional information related to the current slide, or implementing custom animations.

Integrating with other libraries

SwipeJS is designed to be lightweight and dependency-free. This makes it easy to integrate with other JavaScript libraries. For instance, you could combine SwipeJS with a lightbox library to create a swipe-enabled gallery where clicking on a thumbnail opens a larger version in a lightbox. Or you might use SwipeJS with a parallax scrolling library to create more visually engaging transitions between slides. Remember to consider potential conflicts or overlaps in functionality and event handling when integrating with other libraries.

Handling Multiple Swipe Areas

If you need to have multiple swipe areas on a single page, you simply create a separate Swipe instance for each area. Each instance will operate independently. Remember to use unique IDs for each slider element to ensure that each Swipe instance targets the correct element. For example:

<div id="slider1" class="swipe">...</div>
<div id="slider2" class="swipe">...</div>

<script>
  var slider1 = new Swipe(document.getElementById('slider1'), options);
  var slider2 = new Swipe(document.getElementById('slider2'), options);
</script>

Performance Optimization

For optimal performance, especially when working with many slides or large images, consider these optimizations:

Remember that specific optimization techniques may vary depending on the complexity of your project and the number of slides. Profiling your application can help identify performance bottlenecks.

Troubleshooting

Common Issues

Debugging Tips

Error Handling

SwipeJS itself doesn’t have extensive built-in error handling mechanisms. Most errors manifest as unexpected behavior (e.g., the slider not working, slides not transitioning, or JavaScript errors in the console). Focus your error handling on checking for potential issues before initializing the SwipeJS instance. For example, verify that the target element exists and that the necessary configuration options are valid. Use try...catch blocks around the SwipeJS initialization code to catch potential errors during library loading or instance creation.

Browser Compatibility

SwipeJS is generally compatible with modern browsers. However, very old or outdated browsers might not support the required features (like touch events or CSS transitions). Thorough testing across different browsers and devices is recommended, especially if targeting older platforms or less commonly used browsers. While SwipeJS strives for broad compatibility, some minor rendering differences or inconsistencies across browsers might be unavoidable. Always test your implementation to ensure it behaves as expected across your target user base’s browsers.

Examples

Simple Swipe Navigation

This example demonstrates basic swipe navigation between simple divs.

HTML:

<div id="mySwipe" class="swipe">
  <div class="swipe-wrap">
    <div>Slide 1</div>
    <div>Slide 2</div>
    <div>Slide 3</div>
  </div>
</div>

JavaScript:

var mySwipe = new Swipe(document.getElementById('mySwipe'));

This sets up a slider with three slides containing the text “Slide 1,” “Slide 2,” and “Slide 3.” No additional configuration is needed for this basic example.

This example creates a simple image carousel.

HTML:

<div id="imageCarousel" class="swipe">
  <div class="swipe-wrap">
    <div><img src="image1.jpg" alt="Image 1"></div>
    <div><img src="image2.jpg" alt="Image 2"></div>
    <div><img src="image3.jpg" alt="Image 3"></div>
  </div>
</div>

JavaScript:

var imageCarousel = new Swipe(document.getElementById('imageCarousel'), {
  speed: 500, // Adjust speed if needed
  auto: 3000   // Autoplay every 3 seconds (set to 0 to disable)
});

This creates an image carousel that auto-advances every 3 seconds. Remember to replace "image1.jpg", "image2.jpg", and "image3.jpg" with the actual paths to your images.

Interactive Menu

This example shows how to use SwipeJS to create a swipe-able menu.

HTML:

<div id="menu" class="swipe">
  <div class="swipe-wrap">
    <div>Menu Item 1</div>
    <div>Menu Item 2</div>
    <div>Menu Item 3</div>
  </div>
</div>

JavaScript:

var menuSwipe = new Swipe(document.getElementById('menu'), {
    callback: function(index) {
        // Perform actions based on the selected menu item
        console.log("Menu item " + (index + 1) + " selected");
        // Example: Show content related to the selected menu item.
    }
});

This creates a swipe-able menu where selecting an item triggers the callback function, allowing you to perform actions like showing content related to the selected item.

Custom Swipe Actions

This example demonstrates adding custom actions using the callback function.

HTML: (Same as simple swipe navigation example)

<div id="mySwipe" class="swipe">
  <div class="swipe-wrap">
    <div>Slide 1</div>
    <div>Slide 2</div>
    <div>Slide 3</div>
  </div>
</div>
<p id="slideInfo"></p>

JavaScript:

var mySwipe = new Swipe(document.getElementById('mySwipe'), {
  callback: function(index) {
    document.getElementById('slideInfo').innerHTML = "Current slide: " + (index + 1);
  }
});

This example updates a paragraph element (slideInfo) to display the current slide number after each swipe. This showcases how the callback function can be used to perform custom actions based on the current slide. Remember to adapt the HTML to include the slideInfo paragraph.