Skip to content Skip to sidebar Skip to footer

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 men

Solution 1:

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

var timer;
    //Time of the long pressconst tempo = 1000; //Time 1000ms = 1sconstmouseDown = () => {
        timer = setTimeout(function(){ 
                //Insert your function herealert("Your Function Here!");
        }, tempo);
    };
    constmouseUp = () => {
        clearTimeout(timer);
    };
<pontouchstart="mouseDown()"ontouchend="mouseUp()"onmousedown="mouseDown()"onmouseup="mouseUp()">Long Touch Me!</p>

Solution 2:

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

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

Solution 3:

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}
<divid="shot">Touch </div>

Solution 4:

I know it isn't exactly the solution that you've been looking for, but it is a solution that worked for me in many web apps. Instead of letting the user copy/paste it by himself, I'm adding a copy button. For the most part, I believe this results in better user experience.

There are a few libraries that do exactly that with a very small footprint that does not rely on Adobe Flash to do so.

I've been using clipboard.js for a while, it works great on mobile as well.

Post a Comment for "Simulate Long Press In Javascript"