Search code examples
javascriptmobiledrag-and-droptouchmootools

separate touch and scroll on mootools drag


I have a mootools drag window working good on desktop computers and I found this answer about how to make mootools drag support touch events.

When I drag on mobile (IOS), with the Class.refactor applied, the scroll event is also fired. So the draggable window moves and the screen scrolls at same time.

Question: is there a way to disable/suspend scroll when the drag event is "moving"? or when mouse/touch is inside drag div area?

Fiddle example here

And my code (with mootools 1.3.2)

Answer:
document.getElement('.dragme').ontouchmove = function() {event.preventDefault();}(explanation in the answer bellow)

html:

<div class="container">
<div class="dragme">drag me</div>
</div>

JS:

Class.refactor(Drag.Move,
{
    attach: function(){
        this.handles.addEvent('touchstart', this.bound.start);
        return this.previous.apply(this, arguments);
    },

    detach: function(){
        this.handles.removeEvent('touchstart', this.bound.start);
        return this.previous.apply(this, arguments);
    },

    start: function(event){
        document.body.addEvents({
            touchmove: this.bound.check,
            touchend: this.bound.cancel
        });
        this.previous.apply(this, arguments);
    },

    check: function(event){
        if (this.options.preventDefault) event.preventDefault();
        var distance = Math.round(Math.sqrt(Math.pow(event.page.x - this.mouse.start.x, 2) + Math.pow(event.page.y - this.mouse.start.y, 2)));
        if (distance > this.options.snap){
            this.cancel();
            this.document.addEvents({
                mousemove: this.bound.drag,
                mouseup: this.bound.stop
            });
            document.body.addEvents({
                touchmove: this.bound.drag,
                touchend: this.bound.stop
            });
            this.fireEvent('start', [this.element, event]).fireEvent('snap', this.element);
        }
    },

    cancel: function(event){
        document.body.removeEvents({
            touchmove: this.bound.check,
            touchend: this.bound.cancel
        });
        return this.previous.apply(this, arguments);
    },

    stop: function(event){
        document.body.removeEvents({
            touchmove: this.bound.drag,
            touchend: this.bound.stop
        });
        return this.previous.apply(this, arguments);
    }
});
new Drag.Move(document.getElement('div.container'), {
handle: document.getElement('.dragme'),
modifiers: {
    x: 'margin-left',
    y: 'margin-top'
}
});

Solution

  • add an event handler for onTouchMove that does nothing but event.preventDefault - it should stop the scroll/zoom/pinch stuff. you can probably add this within your this.bound callbacks and attach to document.body or on the actual draggable element.