Touch Scrolling in Ace Editor

024th Dec 2014Development, , , , ,

ace-logo I’ve run across an interesting issue that no one seems to be able to solve…so I tackled it. The solution doesn’t offer momentum scrolling or any of that other fancy stuff, but it could be implemented.

Essentially, Ace Editor was written with the mouse in mind. They didn’t do a lot of work on supporting touch events. Specifically you can’t scroll at all on a touch-enabled device. First thing you need to do is encapsulate your Ace Editor in a div.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$('#container').on('touchmove', function(e) {
    e.preventDefault();
    var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0],
        elm = $(this).offset(),
        x = touch.pageX - elm.left,
        y = touch.pageY - elm.top;
    if (x < $(this).width() && x > 0 && y < $(this).height() && y > 0) {
        var editor = ace.edit('editor1'),
            xDiff = x - window.SyntaxEditor_scrollStart_X,
            yDiff = y - window.SyntaxEditor_scrollStart_Y;
        editor.renderer.scrollBy(-xDiff, -yDiff);
        window.SyntaxEditor_scrollStart_X = x;
        window.SyntaxEditor_scrollStart_Y = y;
    }
});

And that’s it. This code should be included after your code to instantiate your editor, and assumes your outer div’s ID is container and your Ace Editor’s ID is editor1. You may also want to change how you store the starting X and Y values. In this example I use variables in the window object (window.SyntaxEditor_scrollStart_X and window.SyntaxEditor_scrollStart_X), but this could easily be added to an object of some sort. I had contemplated building an extension for this, but it works for my needs as-is. Also, it would somewhat trivial to convert this to work without jQuery (or to work with any other framework).

If you make any changes, like added momentum-based or scaled scrolling, I’d love to see it.

No Comments Comments Feed

Add a Comment

Before you post, please prove you are sentient.

What is 5 * 4?