Clicking once or twice on a single element does not produce any results in Javascript

I am trying to implement a click function that activates when a button is clicked. Additionally, I want to incorporate a double click function on the same element that initiates a different action.

var click = false;
onEvent("image2", "click", function(event) {
  click = true;
});
if (click === true) {
  setTimeout(function() {
    onEvent("image2", "click", function(event) {
      setScreen("safeScreen");
      console.log("double click");
    });
  }, 200);
} else {
  onEvent("image2", "dblclick", function(event) {
    setScreen("safeScreen");
    console.log("click");
  });
}

This code seems to be erroneous, and I am unsure where to begin fixing it. What mistakes have I made? My goal is to ensure that the single click does not activate when the user performs a double click.

Answer №1

Update:

For a more efficient approach, consider passing the function clicks() to your event listener like this:

onEvent("image2", "click", clicks);

The function clicks() will determine whether there was a single or double click based on the setTimeout function. You can customize the duration of the setTimeout using the timeout variable and ensure that the clickCount variable is declared outside the clicks() function.


A Simplified JavaScript Solution

Another option would be to implement two event listeners for a cleaner code structure. Take a look at this functional example below.

var selector = document.getElementById('codeorg');
selector.addEventListener('click', clicks);

// Global Scope variables needed
var clickCount = 0;
var timeout = 500;

function clicks() {
  // Incrementing click count to determine number of clicks
  
      clickCount++;
      if (clickCount == 1) {
        setTimeout(function(){
          if(clickCount == 1) {
            console.log('singleClick');
            // Execute single click functionality here 
          } else {
            console.log('double click');
            // Execute double click functionality here 
          }
          clickCount = 0;
        }, timeout || 300);
      }
}

// Not relevant to your specific requirements - additional JS functionality
var button = document.getElementById('button');

button.addEventListener('click', singleClick);
button.addEventListener('dblclick', doubleClick);

function singleClick() {
  //console.log('single click');
}

function doubleClick() {
  console.log('double click');
}
#codeorg {
  margin-bottom: 100px;
}
<h2>Double Click</h2>

<button id="button">Click me</button>


<hr><hr>


<h2>Double click or Single Click</h2>

<button id="codeorg">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

Remove the model from operation

I'm fairly new to angularjs and have a working service. However, I want to move the patient model out of the service and into a separate javascript file. I believe I need to use a factory or service for this task, but I'm not entirely sure how to ...

Design an unordered list containing a text input field and a clickable button

I need assistance with creating a feature where text input is converted into a list when a button is clicked. Here's what I currently have: <!doctype html> <html> <head> <meta charset="UTF-8"> <title>3-2</title> & ...

Unlocking the Secrets: Retrieving Message Embeds Using Discord.js' Message ID

I've been working on creating an advanced suggestion command and here is the progress I've made with the code: if (command === 'accept') { try { const suggestionchan = bot.channels.cache.get('840493081659834403'); const a ...

Clone the children of an li element using jQuery, modify the text within a child tag, and then add it to

I have some awesome CSS that I want to recycle within a <ul>. My plan is to duplicate an existing <li> (to leverage the CSS), modify a <p> element, and then add it at the end of the <ul>. I believe I can achieve this by locating... ...

Oops! There was an issue with building the module in ./src/index.js using babel-loader

I'm running into issues setting up ReactJs from scratch. Whenever I try to use npm start, dev, build, or watch, I encounter the error shown below: ERROR in ./src/index.js Module build failed (from ./node_modules/babel-loader/lib/index.js): SyntaxError ...

Error: The function bind is not supported on instance[method] in the AdonisJs framework

I am currently integrating the MQTT-adonis module adonis-mqtt response on Git here in my adonis-js application. However, when trying to serve it, an exception is thrown. TypeError: instance[method].bind is not a function Could anyone provide guidance o ...

How can we access parameters in ag-Grid's Angular 1 onFilterModified event?

Currently, I am incorporating grid options using the code snippet provided below: var gridOptions = { columnDefs: columnDefs, rowData: null, enableFilter: true, onFilterChanged: function() {console.log('onFilterChanged');}, onFilterModified: fun ...

Looping through elements with jQuery's `each` method within another `

When using div containers in my code, I wanted to loop over them and then iterate through the items within each container. Instead of $('.stackContainer .stackItem').each(, I was looking for a solution like this: // setup stacks $('.stackC ...

Combining Two Models in Sails.js

I'm facing an issue with linking two models in sails. I have two models: 'Singer' and 'Country'. In the 'Singer' model, I have an attribute 'singer_country' which represents the id of the 'Country' mod ...

What is the best way to incorporate correct reference logic when utilizing Joi validation?

I am currently working on designing a straightforward schema to validate inputted number ranges. The condition is that the start value should be less than the end value, and conversely, the end value must be greater than the start value. Below is the sche ...

Ways to divide a string in javascript

Looking to split a string to retrieve the value before the pipe (|). let str = "110|paris"; The goal is to store the value after splitting like this: let value = 100; ...

How to Handle the Absence of HTML5 Spellcheck in Specific Web Browsers

While HTML5 spellcheck functionality may vary across different browsers, there are instances where it might not be supported in certain corporate environments. In the event that HTML5 is not supported in a particular browser, it's essential to first c ...

Unexpected bug encountered while implementing redux

I received a warning from eslint while working with create-react-app. ./src/components/auth.js Line 24: Unexpected labeled statement no-labels Line 24: 'authenticated:' is defined but never used ...

What is the process for adding texture to a model that has been imported using OBJLoader?

I've been immersed in my little project using three.js, but I'm facing a challenge with mapping textures on objects loaded by THREE.OBJLoader. Interestingly, there are no issues with three.js built-in geometry. I find myself quite perplexed... / ...

Is there a way to extract all the class names from a JavaScript file?

I am currently working on developing a code to showcase all the public properties of a class that are available in a JavaScript file. As of now, the user has to manually input the name of the class in a text box. However, my goal is to enhance user experie ...

Documentation for Lambda function within an object

Looking to properly document the sock and data variables using JSDoc in my code. var exec = { /** * @param {Number} sock * @param {String} data */ 1: (sock, data) => { console.log("GG"); }, 2: (sock, data ...

Incorporate a click function onto the image within the canvas

After creating a canvas and placing an image on it, I realized that I need to include a click event for that image. Below is the code snippet I have written in attempt to achieve this. <canvas id="myCanvas" width="578" height="1000"></canvas> ...

Using JsGrid to efficiently load nested object data into a table

Currently, I am in the process of developing a web project using Django and implementing jsGrid. However, I have encountered an issue for which I cannot seem to find a solution. The problem lies with my nested JSON data that is generated by merging record ...

Data loading issue with asp.net mvc Ajax

I am currently facing an issue while attempting to fetch data from the controller using ajax. Controller [HttpGet] public ActionResult GetServices() { var data = _bbdb.ListServices.Where(d => d.Status == true).ToList(); return Json(data, JsonR ...

JavaScript error: "null or not an object" bug

I have implemented the JavaScript code below to display horizontal scrolling text on the banner of my website. Surprisingly, it works perfectly fine on one server but throws an error on another server with the message: Error: 'this.mqo' is nul ...