Keep menu from closing when using touch events

650 views Asked by At

I have hooked up a simple long touch function that after 500ms uses the "open" API command to open the context menu. The menu opens. However, on "touchend" the menu disappears. It only stays if I touchmove over the context menu before "touchend". Is there a way to prevent this sort of behaviour? From the source code, only a "touchstart" in a different part of the dom should trigger a close event.

Code is below, in case useful. Not that a delegate of tr is required by my context menu - to explain the targetTr variable use below.

var mobDevice_onLongTouch,
    mobDevice_touchTimer,
    mobDevice_longPressDuration = 500; //length of time we want the user to touch before we do something

//handle long press on the datatable
var touchArea = document.querySelector("#table");
touchArea.addEventListener("touchstart", touchAreaTouchStart, false);
touchArea.addEventListener("touchend", touchAreaTouchEnd, false);

function touchAreaTouchStart(e) {
    var targetTr = $(e.target).closest('tr');
    mobDevice_touchTimer = setTimeout(function () { touchArea_onLongTouch(targetTr) }, mobDevice_longPressDuration)
};
function touchAreaTouchEnd(e) {
    if (mobDevice_touchTimer) {
        clearTimeout(mobDevice_touchTimer) //reset the clock
    }
};

function touchArea_onLongTouch(target) {
    $('#table').contextmenu('open', target);
};
1

There are 1 answers

0
Simon On

I solved this. ContextMenu was working fine, but the DOM control I was touching on registered a change event (to highlight a table row) on touchend. So the context menu popped up during touch and hold, then got cleared by a DOM change at touchend.

The solution was to manually add the highlight table row event to touchstart and preventDefault on touchend (when the touch target was inside the table)