Skip to content

Swipe

The Swipe Component adds touch and mouse swipe gesture detection to elements. It allows you to detect swipe gestures in four directions: left, right, up, and down.

This component has no additional dependencies beyond the core Metro UI library.

<div id="swipeElement" data-role="swipe">
<div class="p-4">
Swipe me in any direction
</div>
</div>
<div data-role="swipe" data-on-swipe="mySwipeHandler">
<div class="p-4">
Swipe me in any direction
</div>
</div>
<script>
function mySwipeHandler(start, swipe, direction) {
console.log('Swiped in direction:', direction);
}
</script>
// Initialize with JavaScript
Metro.makePlugin('#swipeElement', 'swipe', {
swipeThreshold: 50,
onSwipe: function(event, data) {
console.log('Swipe detected in direction:', data.direction);
},
onSwipeLeft: function(event, data) {
console.log('Swiped left!');
},
onSwipeRight: function(event, data) {
console.log('Swiped right!');
},
onSwipeUp: function(event, data) {
console.log('Swiped up!');
},
onSwipeDown: function(event, data) {
console.log('Swiped down!');
}
});
ParameterTypeDefaultDescription
swipeThresholdNumber32The minimum distance (in pixels) required for a swipe to be detected
  • destroy() - Removes the element from the DOM.
const swipeComponent = Metro.getPlugin('#swipeElement', 'swipe');
swipeComponent.destroy();
EventDescription
onSwipeTriggered for any swipe direction with direction information
onSwipeRightTriggered specifically for right swipes
onSwipeLeftTriggered specifically for left swipes
onSwipeUpTriggered specifically for upward swipes
onSwipeDownTriggered specifically for downward swipes
onSwipeCreateTriggered when the swipe component is created

The event callbacks receive data with the following properties:

{
start: {x: Number, y: Number}, // Starting coordinates of the swipe
swipe: {x: Number, y: Number}, // Swipe distance in x and y directions
direction: String // Direction of the swipe: "left", "right", "up", or "down"
}

For direction-specific events (onSwipeLeft, onSwipeRight, onSwipeUp, onSwipeDown):

Section titled “For direction-specific events (onSwipeLeft, onSwipeRight, onSwipeUp, onSwipeDown):”
{
start: {x: Number, y: Number}, // Starting coordinates of the swipe
swipe: {x: Number, y: Number} // Swipe distance in x and y directions
}

This component does not have specific CSS variables for styling as it’s primarily a behavior component that adds gesture detection functionality.

This component does not add any specific CSS classes beyond setting user-select: none on the element to prevent text selection during swipe gestures.

  • The component automatically adds user-select: none to the element to prevent text selection during swipe gestures.
  • The component works with both touch events (for mobile devices) and mouse events (for desktop).
  • Swipe detection is based on the distance moved in pixels compared to the swipeThreshold value.