简体   繁体   中英

How to prevent “scroll” when a “touchstart” event is fired

I have an scrollable element to which I have added two event handlers ("touchstart" and "scroll"). Both work perfectly fine if fired by themselves. However, when the "touchstart" event is fired, I need to prevent the "scroll" from being fired, but I still need the "scroll" event to be available. The reason is that both events call the same function and so it is causing the app to look buggy when the logic runs many times.

I have created a basic fiddle and here is the link:

http://jsfiddle.net/alejandro1585/0t7v76m7/3/

HTML:

 <div class="main-container">
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
    Hello world
</div>

CSS:

.main-container{
    border:  1px solid red;
    width: 120px;
    height:200px;
    overflow-y: auto;
}

JAVASCRIPT:

    function myFunction(e) {
    console.log("myFunction is being executed", e);
};

/*Method adds handlers to the scrollable list so that functions to show or hide the header can be triggered*/
var scrollShowHideHeaderInit = function () {
    var divObject = document.getElementsByClassName("main-container"); //Scrollable element object

    for (var i = 0; i < divObject.length; i++) {
        divObject[i].addEventListener("scroll", myFunction);
        divObject[i].addEventListener("touchstart", myFunction);
    };
};

scrollShowHideHeaderInit();

You should be able to just stop event propagation on touch start and still maintain scroll-ability

function touch(e){
  console.log("touch", e);
  e.stopPropagation();
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM