Skip to content

Commit

Permalink
Add LongPress support to mobile. Fires a contextmenu event after a si…
Browse files Browse the repository at this point in the history
…ngle press without movement of 1 second
  • Loading branch information
danzel committed Oct 30, 2012
1 parent 3c7b66b commit d133c86
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 0 deletions.
1 change: 1 addition & 0 deletions build/deps.js
Expand Up @@ -170,6 +170,7 @@ var deps = {
src: ['dom/DomEvent.js',
'dom/DomEvent.DoubleTap.js',
'dom/DomEvent.MsTouch.js',
'dom/DomEvent.LongPress.js',
'core/Handler.js',
'map/handler/Map.TouchZoom.js'],
deps: ['MapAnimationZoom'],
Expand Down
1 change: 1 addition & 0 deletions debug/leaflet-include.js
Expand Up @@ -17,6 +17,7 @@
'dom/DomEvent.js',
'dom/DomEvent.DoubleTap.js',
'dom/DomEvent.MsTouch.js',
'dom/DomEvent.LongPress.js',
'dom/DomUtil.js',
'dom/Draggable.js',

Expand Down
60 changes: 60 additions & 0 deletions src/dom/DomEvent.LongPress.js
@@ -0,0 +1,60 @@
L.Util.extend(L.DomEvent, {
// inspired by Zepto touch code by Thomas Fuchs
addLongPressListener: function (obj, handler, id) {
var touch,
start,
timeoutId = null,
delay = 1000,
maxMovement = 10,
diffX, diffY,
pre = '_leaflet_',
touchstart = 'touchstart',
touchmove = 'touchmove',
touchend = 'touchend';

function onTouchStart(e) {
clearTimeout(timeoutId);

if (e.touches.length !== 1) {
return;
}

touch = e.touches[0];
start = Date.now();

timeoutId = setTimeout(function () {
touch.type = 'contextmenu';
handler(touch);
}, delay);
}

function onTouchMove(e) {
diffX = e.touches[0].pageX - touch.pageX;
diffY = e.touches[0].pageY - touch.pageY;

if (diffX * diffX + diffY * diffY > maxMovement * maxMovement) {
clearTimeout(timeoutId);
}
}

function onTouchEnd() {
clearTimeout(timeoutId);
}
obj[pre + touchstart + id] = onTouchStart;
obj[pre + touchmove + id] = onTouchMove;
obj[pre + touchend + id] = onTouchEnd;

obj.addEventListener(touchstart, onTouchStart, false);
obj.addEventListener(touchmove, onTouchMove, false);
obj.addEventListener(touchend, onTouchEnd, false);
return this;
},

removeLongPressListener: function (obj, id) {
var pre = '_leaflet_';
obj.removeEventListener(obj, obj[pre + 'touchstart' + id], false);
obj.removeEventListener(obj, obj[pre + 'touchmove' + id], false);
obj.removeEventListener(obj, obj[pre + 'touchend' + id], false);
return this;
}
});
3 changes: 3 additions & 0 deletions src/dom/DomEvent.js
Expand Up @@ -21,6 +21,9 @@ L.DomEvent = {
} else if (L.Browser.touch && (type === 'dblclick') && this.addDoubleTapListener) {
return this.addDoubleTapListener(obj, handler, id);

} else if (L.Browser.touch && (type === 'contextmenu') && this.addLongPressListener) {
return this.addLongPressListener(obj, handler, id);

} else if ('addEventListener' in obj) {

if (type === 'mousewheel') {
Expand Down

0 comments on commit d133c86

Please sign in to comment.