Making swipe-able websites with JavaScript

Making swipe-able websites with JavaScript

In today's web landscape, touch screens are everywhere: phones, tablets, and even laptops. With so many devices relying on touch, it's important for web developers to understand swiping and how to program it into their websites. The key component of this is handling swipe events in JavaScript.

Swipe gestures are super common across the web. Think about how often you swipe left or right to browse photos, scroll through lists, or to manage messages. Knowing how to manage these swipes can make your apps feel smooth and responsive.

Reasons To Study Swiping in JavaScript

  1. Better User Experience: Users expect smooth interactions on their touch devices. By handling swipes well, you make your app easier and more enjoyable to use.

  2. Stay Competitive: Good swiping mechanics on your site can set you apart from other, less experienced developers. If your app feels clunky or outdated on mobile apps, this can make your applications seem clunky and non-optimized.

  3. Unlock Creativity: Knowing how to handle swipes opens up new possibilities for fun and innovative features in your app. It lets you think outside the box and create unique experiences.

In this article, we'll break down how to handle swipe events in JavaScript, helping you build better, more user-friendly apps.

Swipe Events in JavaScript

JavaScript has the ability to handle many events, such as clicking, swiping, scrolling etc. We must utilize these events to make custom swiping functionality.

Here are the swiping events utilized by JavaScript

  • touchstart: Triggered when the touch starts.

  • touchmove: Triggered when the touch moves.

  • touchend: Triggered when the touch ends.

Implementation

Here we will build an example of a swipe-able component in JavaScript

The HTML and CSS

<div class="carousel-container">
  <button class="carousel-button left">&lt;</button>
  <div class="carousel">
    <!-- Add your carousel items here -->
    <div class="carousel-item">Item 1</div>
    <div class="carousel-item">Item 2</div>
    <div class="carousel-item">Item 3</div>
  </div>
  <button class="carousel-button right">&gt;</button>
</div>

<style>
.carousel-container {
  position: relative;
  width: 100%;
  overflow: hidden;
}

.carousel {
  display: flex;
  transition: transform 0.5s ease-in-out;
  padding: 0 32px;
}

.carousel-item {
  min-width: calc(100% / 3);
  box-sizing: border-box;
}

.carousel-button {
  position: absolute;
  top: 0;
  bottom: 0;
  color: #123963;
  border: none;
  cursor: pointer;
  font-size: 38px;
  z-index: 5;
  background-color: #fff;
}

.carousel-button.left {
  left: 0;
}

.carousel-button.right {
  right: 0;
}

@media (max-width: 769px) {
  .carousel-item {
    min-width: 100%;
  }
}
</style>

Notice the left/right buttons are absolutely positioned to the left and right. This is because the carousel items will translate left and right, yet we want these buttons to remain in the same spot

The JavaScript (Handling Swipes)

// runs once all content is loaded on page
document.addEventListener('DOMContentLoaded', function() {

  // grab relevant HTML items 
  const carousel = document.querySelector('.carousel');
  const leftButton = document.querySelector('.carousel-button.left');
  const rightButton = document.querySelector('.carousel-button.right');

  // variables to record swipe status
  let offset = 0;
  let startX;
  let isSwiping = false;

  // have width of each item to ensure clean swipes (not required)
  // will be used to calculate by how much we shift horizontally on swipe
  // you could hardcode a value or just have it move how much you swiped
  const itemWidth = carousel.querySelector('.carousel-item').offsetWidth;

  // Swipe functionality
  // =======================================================

  // When user touches, record the starting point and set isSwiping to true
  carousel.addEventListener('touchstart', (e) => {
    startX = e.touches[0].clientX;
    isSwiping = true;
  });

  // runs as the user's touch moves (swiping)
  carousel.addEventListener('touchmove', (e) => {
    if (!isSwiping) return;
    // record current positioning and difference from beggining
    // using X values since this is a horizontal scroll
    const currentX = e.touches[0].clientX;
    const diffX = startX - currentX;

    // if this difference is over +50, we Swipe Left
    if (diffX > 50) { 
      const maxOffset = (carousel.children.length - 1) * itemWidth;
      if (offset < maxOffset) {
        offset += itemWidth;
        carousel.style.transform = `translateX(-${offset}px)`;
      }
      isSwiping = false;

    // if this difference is below -50, we Swipe Right
    } else if (diffX < -50) { 
      if (offset > 0) {
        offset -= itemWidth;
        carousel.style.transform = `translateX(-${offset}px)`;
      }
      isSwiping = false;
    }
  });

  // Once swipe ends, turn isSwiping to false
  carousel.addEventListener('touchend', () => {
    isSwiping = false;
  });
});

And there you have it! You now have a swipe-able component in your web application! Keep in mind this is easily applicable to other types of swipes with minor tweaks. The main takeaways here should be:

The Events

  1. touchstart: Triggered when the touch starts.

  2. touchmove: Triggered when the touch moves.

  3. touchend : Triggered when the touch ends

Positioning

  • offset : how much the touch has moved

  • translate : a CSS property that moves things along a specific axis

Hope you learned something!