What is the best way to integrate a hold button that triggers a JavaScript function?

Looking to create a button that triggers a JavaScript function when held for 5 seconds and cancels the call upon release. Any suggestions on how I can achieve this?

Here's an example of what I have in mind:

Answer №1

Check out this cool jsfiddle link where an alert will be triggered only if you hold the button for 5 seconds, but will not show up if you release the button earlier. The trick lies in setting a timeout when the button is clicked and then clearing it once the button is released. (using jquery)

Click here to view the demo!

 <div>
  <input id="btnTesting" type="button" value="test" />
</div>

$('#btnTesting').mousedown(function(){
        myTimeout = setTimeout(function(){ alert("Hello"); }, 5000);
});

$('#btnTesting').mouseup(function(){
    clearTimeout(myTimeout);
});

Answer №2

function CustomHandler() {
       // Define a function that sets an action to handle after 5 seconds.
       this.clickEvent = function() {
          var self = this;
          this.scheduleId = setTimeout(function() {
              console.log('Event triggered!');
              self.scheduleId = null;
              // Implement required logic here.
          },5000)
       };
       
       // Define a function that cancels the previously scheduled task.
       this.cancelEvent = function() {
           // Cancel logic if needed
           if (this.timerId) {
               console.log('Canceling event');
               clearTimeout(this.scheduleId);
           }
       }
    }


 
var customHandler = new CustomHandler();

// Locate an element to bind the event to.
var buttonElement = document.querySelector('button');

// Link the event handlers to the element
buttonElement.addEventListener('mousedown', customHandler.clickEvent.bind(customHandler));

buttonElement.addEventListener('mouseup', customHandler.cancelEvent.bind(customHandler));
<button>Click Me</button>

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

Vue application experiencing never-ending update cycle following array assignment

Here is the JavaScript code I am working with: const storage = new Vue({ el: '#full-table', delimiters: ['[[', ']]'], data: { events: [], counter: 0, }, methods: { eventCounter: fu ...

Is a 'Virtual DOM' included in React Native's architecture?

According to the ReactJS wiki page on Virtual DOM: React uses an in-memory cache of data structures to efficiently compute differences and update the displayed DOM in the browser. This allows developers to write code as if the entire page is re-rendered ...

Managing various encoding methods when retrieving the XML data feed

I'm attempting to access the feed from the following URL: http://www.chinanews.com/rss/scroll-news.xml using the request module. However, the content I receive appears garbled with characters like ʷ)(й)޹. Upon inspecting the XML, I noticed that ...

JavaScript Document Object Model: Locate an element with a class that is either similar to or includes a specific substring

I am facing a situation where I need to locate a wrapper element with a specific class name that includes a random id, such as wp-rgtayfu-fxyjzw-wrapper. The class will always have the substring wrapper in it, and there is only one element in the document ...

Tips for consistently obtaining the executed value of a getter in Mongoose?

In my mongoose schema, I have implemented a getter function for one of the properties as shown below: const User = new mongoose.Schema( { active: Boolean, email: {type: String, get: toLowerCase} } ) The toLowerCase function is def ...

Encountering a problem when using the routingService to navigate inside a JavaScript function

Within my Angular component, I have a method called onCellPrepared. In this method, I am using jQuery to attach a span tag. I want to be able to trigger an Angular service to navigate to another page when the span tag is clicked. How can I successful ...

What is the method to designate the initial value of a <select> tag within a React component?

I am working with a basic <select> element that is looping through a set of options: <select onChange={(event) => this.setState({selectedOption: event.target.value }) }> { this.state.options.map(option => <option key={option.label} ...

Building a single class in Node.js Express for use across multiple routes

In my project, I am developing APIs in the routes folder. How can I create a validation class to ensure that certain objects are not empty, null, undefined, or contain errors, and then use it across all routes? For instance, when creating a new user via a ...

What is the best way to save personalized CSS styles into a database?

Appreciation for assisting others and contributing to open source projects. I have developed a Vue.js to-do application that stores data in Firebase using vue-fire and Firestore. One issue I am experiencing is that the styling, such as "line-through" for ...

The PointCloud vertices in Three.js consistently provide a position of (0,0,0)

I'm working with a PointCloud named "cloud" that is centered at (0, 0, 0) and consists of approximately 1000 vertices. These vertices' positions are being manipulated by a vertex shader. My goal now is to log the position of each vertex to the co ...

Modifying an image on a website with XML information and jQuery

I'm in the process of revamping my website's HTML structure and switching to using an XML file for content. The jQuery script I have is as follows: <script> function extractSiteName() { var URL = window.location.href; var das ...

Issues with HTML/CSS/Javascript functionality occurring on Tablet devices

I recently created a simple HTML page with CSS and JavaScript. The code prompts the user to enter a password, which is then verified by the JavaScript code to display relevant information to the user through alerts. While this code works fine on my desktop ...

Issue found: React-Redux action is not being dispatched

I'm currently working on setting up Google authentication in my React Next.js application. The process involves sending the access token to my backend, where it is validated before a new token is returned in the header for accessing protected resource ...

The data remains stagnant and unchanging, consistently showing the same result even after the project has been deployed

In my Next.js v13.2 application, I developed an API endpoint that retrieves data from a database. app/api/someData Everything was functioning perfectly until I deployed it on Vercel. It seems like the issue lies in the caching of the route, leading to the ...

Production environment sees req.cookies NEXTJS Middleware as undefined

Here is my latest middleware implementation: export async function middleware(request: NextRequest) { const token = request.headers.get('token') console.log(token) if (!token || token == undefined) { return NextResponse.redirect(new URL('/lo ...

Updating the rotational pivot of an object following a positional shift

After moving my object with the "w" key and then rotating it with the "x" key, I noticed that my object rotates around the world origin instead of its own center. How can I update the object's pivot after moving it? I've come across suggestions t ...

Creating a merged object from a split string array in TypeScript

I possess an array containing objects structured as follows; const arr1 = [ {"name": "System.Level" }, {"name": "System.Status" }, {"name": "System.Status:*" }, {"name": "System.Status:Rejected" }, {"name": "System.Status:Updated" } ] My object ...

Switching a JavaScript variable to PHP

I understand that this question may have been asked numerous times and could potentially be marked as a duplicate, but I really need the code because I'm struggling to grasp it. I currently have a variable called x in my JavaScript file and I want t ...

Unable to view the image in browsers other than Internet Explorer

On a webpage, there is a feature where clicking on the "Add More" link should display an input box and a "Delete" button image. Surprisingly, this functionality works perfectly on IE browsers, but not on Mozilla or Chrome. In non-IE browsers, only the text ...

Save user entries in a database array

I'm working on developing a platform for advertisements where users can create detailed profiles with images. To achieve this, I need to store the information in an array within a backend database for future retrieval. Below is an example of the backe ...