Search code examples
javascriptcode.org

Single click and Double click on the same element, not working; Javascript


I am trying to add a click function that triggers when a button is clicked. I am also trying to figure out how to add a double click function onto the same element, that triggers a different event.

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 is completely wrong, but I don't know where to start/correct. What am I doing wrong? I am looking to have the single click not trigger when the user double clicks.


Solution

  • Update:

    Try passing a function clicks() to your event listener like so:

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

    Function clicks() will check if there was a single or double click based on setTimeout function. You can adjust setTimeout via timeout variable and of course you need clickCount variable declared outside clicks() function.


    Pure js approach

    Try adding two event listeners. Less code, much cleaner. Check this working example.

    var selector = document.getElementById('codeorg');
    selector.addEventListener('click', clicks);
    
    
    // Global Scope variable we need this
    var clickCount = 0;
    // Our Timeout, modify it if you need
    var timeout = 500;
    // Copy this function and it should work
    function clicks() {
      // We modify clickCount variable here to check how many clicks there was
      
          clickCount++;
          if (clickCount == 1) {
            setTimeout(function(){
              if(clickCount == 1) {
                console.log('singleClick');
                // Single click code, or invoke a function 
              } else {
                console.log('double click');
                // Double click code, or invoke a function 
              }
              clickCount = 0;
            }, timeout || 300);
          }
    }
    
    
    
    // Not important for your needs - pure JS stuff
    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>