Prevent vertical scrolling on touch devices when using the Owl Carousel plugin

Is there a way to prevent vertical scrolling on Owl Carousel when dragging it horizontally on touch devices? It currently allows for up and down movement, causing the whole page to jiggle. If anyone has a solution, I can share the JavaScript file.

Appreciate any help in advance!

Answer №1

Impressive use of CSS3!

.owl-carousel
{
    -ms-touch-action: pan-y;
    touch-action: pan-y;
}

Answer №2

This method has been effective for me, particularly on iOS devices. I have not yet tested it on Android.

During my experimentation, I observed that Owl Carousel adds the .owl-grab class to the slider when sliding with a mouse or touch input. Inspired by @Turnerj's code, I added .owl-grab to the existing code snippet.

Here is a helpful resource on disabling scrolling during touch movement on specific elements.

This solution also supports multiple sliders on the same page. It may not be perfect due to my limited experience with jQuery.

window.blockMenuHeaderScroll = false;
$(window).on('touchstart', function(e) {
    if ($(e.target).closest('.owl-grab').length == 1) {
        blockMenuHeaderScroll = true;
    }
});
$(window).on('touchend', function() {
    blockMenuHeaderScroll = false;
});
$(window).on('touchmove', function(e) {
     if (blockMenuHeaderScroll) {
        e.preventDefault();
     }
});

Answer №3

When working with Classes, consider using hammer.js in conjunction with addEventListener. My experience testing this on iOS (iPhoneX) and Android (Nexus 5X) has been very positive. I believe this solution could be valuable to others!

window.blockMenuHeaderScroll = true;
        var mc = new Hammer(document);
        var classname = document.getElementsByClassName("elenco_image");

        mc.on("swipeleft swiperight panleft panright", function(ev) {
            console.log(ev.type + " gesture detected.");
            window.blockMenuHeaderScroll = true;
        });

        mc.on("swipeup swipedown panup pandown", function(ev) {
            console.log(ev.type + " gesture detected.");
            window.blockMenuHeaderScroll = false;
        });

        for (var i = 0; i < classname.length; i++) {
            classname[i].addEventListener('touchmove', function(evt) {
                if (blockMenuHeaderScroll) {
                    evt.preventDefault();
                }

            }, {
                passive: false
            });
        }

Answer №4

.owl-carousel 
{
-ms-touch-action: pan-x;
touch-action: pan-x; 
}

I found this solution helpful because it allows for only horizontal scrolling. By using the code above, I was able to disable vertical scrolling completely.

Answer №5

To prevent vertical scrolling when dragging the image horizontally, or to block horizontal panning while trying to scroll the page vertically.

Make sure to attach the event directly to the IMG element.

let blockScroll = false;
let blockPan = false;

$('.owl-carousel img').on('touchstart', '', ots);
$('.owl-carousel img').on('touchmove', '', otm);

let p0 = [0,0];

function ots(ev) { //save the initial touch point
  p0 = [ev.touches[0].screenX, ev.touches[0].screenY];
  blockScroll = false;
  blockPan = false;
}

function otm(event){
    if(blockScroll)
      event.preventDefault(); //prevent window from scrolling vertically
    else if(blockPan)
    { //stop OWL from getting the event and panning horizontally.
      event.stopPropagation();
      event.stopImmediatePropagation();
    }
    else
    { //calculate distance from initial touch point on each move
      let t = event.touches[0];
      let dx = t.screenX - p0[0];
      let dy = t.screenY - p0[1];

      if( Math.abs(dx) > Math.abs(dy) )
      {
        blockScroll = true;
        event.preventDefault();
      }
      else
      {
        blockPan = true;
        event.stopPropagation();
        event.stopImmediatePropagation();
      }
    }
}

Successfully tested on android (Chrome) and ios(Safari).

Answer №6

Enhancements made to optimize touch actions for a smoother experience, inspired by @Giovanni Locombi's solution. Specifically tailored for iOS users.

Utilizing the capabilities of Hammer.js available at

    window.blockMenuHeaderScroll = false;
    var mc = new Hammer(document);
    var classname = document.getElementsByClassName("owl-carousel");

    mc.on("swipeleft swiperight panleft panright", function(ev) {
        window.blockMenuHeaderScroll = true;
    });

    mc.on("panend swipeend", function (ev){
        window.blockMenuHeaderScroll = false;
    });

    mc.on("swipeup swipedown panup pandown", function(ev) {
        window.blockMenuHeaderScroll = false;
    });

    for (var i = 0; i < classname.length; i++) {
        classname[i].addEventListener('touchmove', function(evt) {
            if (blockMenuHeaderScroll) {
                evt.preventDefault();
            }

        }, {
            passive: false
        });
    }

Answer №7

After trying numerous solutions without success, I finally found one that fixed the issue.

.owl-carousel .owl-stage, .owl-carousel.owl-drag .owl-item{
    -webkit-touch-action: auto;
        touch-action: auto;
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

"Optimizing the placement of a range slider for pricing options

As a beginner in HTML, CSS and JS, I recently faced the challenge of creating a price slider range on a website. However, I am struggling with repositioning it. After copying the code from this link, I noticed that the slider is positioned at the top of th ...

Exploring Angular testing by using mock services to simulate the behavior of other services

I am familiar with how to mock a function call to a service. However, I am facing a scenario where my MainService acts as a wrapper for multiple other services. export class MainService { constructor( public service1: Service1, public service2 ...

Exploring Nested Views in a MEAN Application using UI Router

I am currently developing a MEAN application and struggling to get my ui-router functioning correctly. Within my index.html template, I have loaded all the necessary javascript and css for my application such as angular, jquery, angular-ui-x, bootstrap. I ...

Retrieving text data in Controller by utilizing jQuery AJAX request

Text box and button for input <input type="text" class="form-control" name="ClaimNumber" placeholder="Enter a claim number" id="ClaimNumber" /> <button class="btn btnNormal" type="submit" id="btnSearch"> ...

Retrieve the URL of the previously visited webpage using Javascript

Is there a way to retrieve the URL of the last visited page using JavaScript? I want to be able to track which product the user viewed most recently. I have attempted the following code: var x = document.referrer; document.getElementById("demo").innerHTML ...

Modifying the font style of text within an HTML string using SQL Server

I need to standardize font sizes in my database where strings are stored as html and users can modify the font size. However, for generating reports, I require all font sizes to be consistent. If I have the following html code, how can I change the font si ...

When utilizing forEach to loop through and interact with elements in React Testing Library, the onClick event handler is not triggered. However, employing a for loop successfully triggers the

In my React project, I've created a functional component called Shop. It accepts a callback function as a prop and displays a list of items. Each item in the list triggers the callback when clicked. function Shop(props) { const { onClickMenu } = p ...

What other choices are available for the Angular ui-select2 directive?

Within the Angular select2 controller below: <select ui-select2 id="projectListSelection" data-placeholder="Select a Project ..." ng-model="selectedProject"> @*ng-options="project.WebsiteName for project in projectList"*@ ...

Exploring techniques to compare two objects in JavaScript and then dynamically generate a new object with distinct values

var person1={ name:"Sarah", age:"35", jobTitle:"Manager" } var person2={ name:"Sarah Sanders", age:"35", jobTitle:"Manager" } //the name value has been updated in the above object, s ...

Can you demonstrate how to incorporate a new line within a for loop?

I have an array of letters and I need to display them on the screen using a for loop. My goal is to make every sixth letter appear on a new line. Here is the code snippet: https://i.stack.imgur.com/lHFqq.jpg <script> export default { data() { ...

Executing jQuery function through variable reference

My goal is to modify the jQuery function being used based on the value of a switch statement. In this scenario, I want to select the element and then apply the appropriate jQuery function depending on the 'direction' parameter. $('#'+t ...

Is there a potential white-space issue with jQuery CSS in Internet Explorer versions 7 and 8

Recently, we encountered an unusual issue with jQuery and CSS while working on compatibility with IE7 and IE8. Our project involves animations and height measurements, and during the animations, we wanted to prevent text from wrapping. To achieve this, we ...

Modify the color of text in Bootstrap navigation bar

I am struggling to adjust the text color within my bootstrap links. I attempted the method mentioned in this post, but unfortunately it did not work for me. Can someone please guide me on how to successfully change the text color? Thank you. You can view t ...

Having trouble getting the jQuery script to properly check file size in an HTML form before uploading?

I've created an HTML form with a jQuery script to verify the file size when the SAVE button is clicked. Despite my efforts, the check doesn't seem to be functioning properly in the HTML Form. Please assist me with this and thank you in advance ...

Refreshing a Thymeleaf table dynamically without having to reload the entire page

I am currently using the Thymeleaf attribute to render data, but I am now looking to add a "Search" button without reloading the page. Within the attribute departments, I am rendering a List<Department> from the database. While I understand how to a ...

Implementing a Custom CSS Theme in JavaFX

Hey everyone, I stumbled upon this amazing JavaFX theme called Flatter on . I've been attempting to implement it for a couple of hours now, but I'm struggling with the process. Can someone provide me with a detailed guide on how to activate thi ...

Storing data using angular-file-upload

In my application, I am utilizing the "angular-file-upload" library to save a file. Here is the code snippet that I am using: $scope.submitForm = function(valid, commit, file) { file.upload = Upload.upload({ url: '/tmp', data ...

Angular CSS: ng-style applied to only one side, the other remains unaffected

I am working on an Angular application that requires a split screen with two halves, each displaying the same array values. The width and height values are set using a service and accessed by a controller. The style is applied using ng-style in the DOM. Ho ...

What is the best way to simulate a service that returns a promise when writing unit tests for AngularJS using Jasmine?

I have a service named myService that relies on another service called myOtherService. The latter makes a remote call and returns a promise. Here's the implementation: angular.module('app.myService', ['app.myOtherService']) .fac ...

What causes a span with absolute positioning to not be correctly positioned within a span with relative positioning in Firefox, unless it is displayed as inline-block or similar?

Can you explain why the code below doesn't display correctly in Firefox unless the parent span is set to display as inline-block? When inspecting the layout of the absolutely positioned span, it shows the number 184 instead of 197 on the right side. A ...