Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate Long Press in Javascript

I have a webapp where when the user clicks on a field, the text inside is highlighted for him to copy. However, on Android this does not trigger the opening of the copy context menu, so the user must select the text himself.

Is there a way to programmatically trigger the long press event so that the copy/paste context menu appears on mobile browsers?

like image 742
Daniel Kats Avatar asked Feb 22 '15 23:02

Daniel Kats


People also ask

How do you make a click in Javascript?

Method 1: Using the click() method: The click() method is used to simulate a mouse click on an element. It fires the click event of the element on which it is called. The event bubbles up to elements higher in the document tree and fires their click events also.

Which function is needed to perform a long press on button element?

addEventListener('long-press', function(e) { // do something });


3 Answers

The following example emulates Android Long press. Put your action after the long press inside the setTimeout:

    var timer;
    //Time of the long press
    const tempo = 1000; //Time 1000ms = 1s
    const mouseDown = () => {
        timer = setTimeout(function(){ 
                //Insert your function here
                alert("Your Function Here!");
        }, tempo);
    };
    const mouseUp = () => {
        clearTimeout(timer);
    };
<p ontouchstart="mouseDown()" ontouchend="mouseUp()" onmousedown="mouseDown()" onmouseup="mouseUp()">Long Touch Me!</p>
like image 93
ZenJB Avatar answered Nov 07 '22 01:11

ZenJB


Maybe you can achieve this by using the taphold event from jquery mobile.

http://api.jquerymobile.com/taphold/

like image 27
fons Avatar answered Nov 07 '22 01:11

fons


From ecma6 javascript, we can use GlobalEventHandlers, to detect keys and touch events. There is a lot of different handlers for different events.

When the user touch/key/click an element, we can detect it in many ways, but for your exact query, a touch/click event is made of two different actions: ontouchstart and ontouchend.

It basically means that when ontouchend isn't triggered, the user is holding the element by touching, this is a long touch/click.

The following example use onmouseover, onmousleave, ontouchstart and ontouchend events.

shot.onmouseover = (function(){
 console.log("Mouse action started!")
})

shot.onmouseleave = (function(){
 console.log("Mouse action terminated!") 
})


shot.ontouchstart  = (function(){
 console.log("Touch action started!") 
})

shot.ontouchend  = (function(){
 console.log("Touch action terminated!") 
})
#shot {width:100%;min-height:300px;background:red}
<div id="shot">Touch </div>
like image 3
NVRM Avatar answered Nov 07 '22 01:11

NVRM