Executing a Long Press in JavaScript

My web application allows users to click on a field and have the text inside highlighted for copying. However, I have noticed that on Android devices, this action does not automatically trigger the copy context menu to appear. Instead, the user must manually select the text.

Is there a method to programmatically activate the long-press event in order to prompt the copy/paste context menu to display on mobile browsers?

Answer №1

To demonstrate an Android Long press simulation, insert your action for after the long press within the setTimeout function:

    var timer;
    //Time duration for long press
    const tempo = 1000; //1 second (1000 milliseconds)
    const mouseDown = () => {
        timer = setTimeout(function(){ 
                //Place your desired function here
                alert("Your Function Here!");
        }, tempo);
    };
    const mouseUp = () => {
        clearTimeout(timer);
    };
<p ontouchstart="mouseDown()" ontouchend="mouseUp()" onmousedown="mouseDown()" onmouseup="mouseUp()">Press and Hold Me!</p>

Answer №2

To accomplish this, consider utilizing the taphold event from jQuery Mobile.

Answer №3

Utilizing ecma6 javascript, the GlobalEventHandlers can be employed to identify keys and touch events. There are various handlers available for different types of events.

When a user interacts with an element through touch/key/click, it can be detected in multiple ways. Specifically, for your query, a touch/click event comprises of two distinct actions: ontouchstart and ontouchend.

This essentially implies that if ontouchend is not triggered, the user is continuously touching the element, which signifies a long touch/click.

The code snippet below demonstrates the use of onmouseover, onmouseleave, 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>

Answer №4

Although it may not be the exact solution you were seeking, I have found a method that has been effective for me in numerous web applications. Instead of relying on users to copy and paste information themselves, I have implemented a convenient copy button. This approach generally leads to an improved user experience.

There are several lightweight libraries available that offer this functionality without requiring Adobe Flash.

Personally, I have had success using clipboard.js for some time now, and it functions well on mobile devices too.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Getting a variable from outside of the observable in Angular - a step-by-step guide

I have an Observable containing an array that I need to extract so I can combine it with another array. this.builderService.getCommercialData() .subscribe( data=>{ this.commercialDetails = data; this.commercialDetailsArr ...

Can CSS Variables be changed globally using jQuery?

How can I dynamically change CSS Variables globally using jQuery? Check out this code snippet: $("div").click(function() { // Update the global variable "--text_color: rgb(0, 0, 255);" to a new value like "--text_color: rgb(0, 255, 255);" }); :roo ...

I am attempting to display only the description of the button that I click on

How can I ensure that only the container pressed will display its description when the description button is clicked, instead of all mapped containers showing their descriptions? `import { useState } from "react"; export default function Se ...

Error encountered when attempting to perform a Fetch POST request with same-origin credentials (Express & React)

I'm currently testing a login process in React that reaches an Express API route; the HTTP request is a POST made using fetch as shown below: const response = await fetch(`http://localhost:3001/login`, { method: "POST", mode: "same- ...

A step-by-step guide to incorporating dependencies in an AngularJS controller

I'm currently working on a MEANJS application and I want to integrate Snoocore into an AngularJS controller. Find more about Snoocore here 'use strict'; angular.module('core').controller('HomeController', ['$scope ...

Merging distinct objects/values in AngularJS/Javascript to create a straightforward list

I possess a dynamically generated, multi-level nested object containing DISTINCT values. My goal is to flatten it (using either AngularJS or vanilla JS) and produce a straightforward array or object for each key/value pair. For example, if the object takes ...

What is the mechanism Angular utilizes to determine the exact location of directives within a webpage?

Can you explain how Angular is able to locate the directives on a webpage and establish connections with or observe those elements? I've searched through the DOM reference, but it seems like methods like getElementbySomething and querySelectorAll may ...

manipulating dropdown visibility with javascript

I'm feeling a bit lost on how to structure this code. Here's what I need: I have 5 dropdown boxes, with the first one being constant and the rest hidden initially. Depending on the option chosen in the first dropdown, I want to display the corres ...

Output Scalable Vector Graphics (SVG) content on a webpage

I need to include an SVG element in my Angular 2+ code. My goal is to provide users with the option to print the SVG element as it appears on the screen. <div class="floor-plan" id="printSectionId2" (drop)="onDrop($event)" (dragover)="onDragOver ...

Using Mongoose, Express, and Node.js to send a server variable to an HTML page

I've encountered an issue while attempting to transfer a variable from my server.js file to HTML. Despite successfully passing the variable to another EJS file on a different route, I can't seem to display it within this specific EJS file. Strang ...

Is there a seamless way to effortlessly upload massive files to s3 through an adminjs dashboard without encountering any glitches?

Attempting to upload large files (40mbs+) to s3 using the @adminjs\upload feature on the adminJS dashboard. While testing locally, most files are successfully uploaded but it takes a considerable amount of time. However, when attempting this on the AW ...

Blender Mesh Not Visible in Three.js

After creating a mesh in Blender, I attempted to use it in three.js. Although the file is being loaded according to the event log, all I see is a black screen. How can I ensure that the mesh actually appears on the screen? import * as THREE from 'thre ...

Scrolling through four limited list items automatically

Hey there! I am currently working on a design project. You can check it out here. I'm trying to replicate a section from another site, which you can see here. <div class="latest-winners-container"> <h3 class="header">Latest Winners< ...

An example of text that includes a link using ES6 template strings

My goal is to display the message "I read and agree to the privacy policy.privacy policy." where the 'privacy policy' part is a clickable link. I attempted the following code but it resulted in "I read and agree to the [object object]." const p ...

React doesn't have file upload configured to update the state

I am working on integrating a file upload button that sends data to an API. To ensure only the button triggers the upload dialog and not the input field, I have set it up this way. Issue: The File is not being saved to state, preventing me from using a ...

How can I execute JavaScript within a PHP loop without generating multiple <script> tags?

I'm currently developing a simple WordPress plugin and I would like to have a portion of it write to the footer. In order to achieve this, I need to utilize an inline script that allows me to call PHP within certain functions that retrieve dates from ...

Choose a specific <div> element by its unique ID and trigger a click event on it as soon as the page loads

There is a div element on my webpage tagged with the ID of #activateeditbutton. I am hoping to have this specific div trigger a click event upon the page's initial loading. In an attempt to achieve this functionality via jQuery, I have written the fo ...

React - Dealing with rendering issue when toggling a button using LocalStorage and State

For quite some time now, I've been struggling with a particular issue... I'm encountering challenges in using the current state to display a toggle button that can both add and remove an item from local storage. The code below manages to add and ...

Achieving success by correctly reaching the window's edge during an event (onscroll)

This happens to be my 1st inquiry. Specifically, I have a navigation menu with a transparent background and I am attempting to alter the background once it reaches the top edge of the window. window.addEventListener("scroll", navSticky); function navSt ...

Babel: deactivate transpilation of import directives

Currently, I am facing a unique challenge with the babel transpiler in my project. The issue is that I am working with an ES5 JavaScript codebase that already includes imports and export directives. For instance: import Widget from 'component:compon ...