Swipe Down to Close in Oxygen Builder Modals using jQuery

In the era of mobile-first design, touch gestures are becoming increasingly important for enhancing user experience. If you're using Oxygen Builder to create WordPress websites, you might be interested in adding touch gestures to your modals. In this blog post, we'll walk you through a simple jQuery script that allows users to swipe down to close a modal in Oxygen Builder.

jQuery(document).ready(function($) {
    let start_y, touchStartTime, touchEndTime;
    const swipeThreshold = 85; // Arbitrary threshold, can be adjusted
    const holdDuration = 500; // Minimum time required for a 'hold' in milliseconds

    $('.ct-modal').on({
        'touchstart': function(e) {
            start_y = e.originalEvent.touches[0].pageY;
            touchStartTime = new Date().getTime();
        },
        'touchend': function(e) {
            const end_y = e.originalEvent.changedTouches[0].pageY;
            touchEndTime = new Date().getTime();

            if (end_y - start_y > swipeThreshold && (touchEndTime - touchStartTime) > holdDuration) {
                $('.oxy-close-modal').trigger('click');
            }
        }
    });
});

Variables

  • start_y: Stores the Y-coordinate where the touch starts.
  • touchStartTime, touchEndTime: Store the time when the touch starts and ends, respectively.

Constants

  • swipeThreshold: The minimum distance the user needs to swipe down to trigger the close action.
  • holdDuration: The minimum time the user needs to hold before the swipe is considered valid.

Event Listeners

  • touchstart: Captures the starting Y-coordinate and time when a touch starts.
  • touchend: Captures the ending Y-coordinate and time when a touch ends, and then checks whether the conditions for a swipe down are met.

Implementation Steps

  • Step 1: Add a Modal element inside Oxygen.
  • Step 2: That's it, we are targeting default classes Oxygen gives to its modal's (.ct-modal).

Adding touch gestures to your Oxygen Builder modals can significantly improve the user experience, especially for mobile users. This jQuery script is a simple yet effective way to implement a swipe-down-to-close feature.

Share this post