Search code examples
javascripthtmlevents

How to apply long click event and doubleclick event on the same element in javascript


I have an element(textArea). Now I would like a long press event and a double click event on the element. I am able to do this but I would also like to use event.preventDefault() in the mousedown event of long press event. This in turn prevents the dblClick event also.

The reason why I want to preventDefault is I am rendering an element on longPress and wanted to prevent the initial mouseDown as I am firing mousemove after longpress. I have searched and re-searched the net but am unable to find a good answer which solves the problem of long press and dblclick on the same element.

thanks!!


Solution

  • Try out this JSFiddle Demo

    HTML

    <p>
    Try it out on this button input:<br><br>
    <input type="button" onmousedown="start(event)" onmouseup="revert()" ondblclick="someFun()" value="hold click for awhile">
    </p>
    <p>
    p.s. This solution also works for non-input elements, e.g. a span or div:
    <div onmousedown="start(event)" onmouseup="revert()" ondblclick="someFun()" style="border: 2px solid #ff0000;">It also works on this div!</div>
    </p>
    

    JavaScript

    const delay = 1500; // Duration in milliseconds of how long you have to hold click.
    let isActive = false;
    let timer;
    
    function start(e) {
      isActive = true;
      timer = setTimeout(makeChange, delay);
      // In case you want to prevent Default functionality on mouse down.
      if (e.preventDefault)  {
        e.preventDefault();
      } else {
        e.returnValue = false; 
      }
    }
    
    function makeChange() {
      if (timer) {
        clearTimeout(timer);
      }
      if (isActive) {
        // .. rest of your code here ..
        alert('long click detected');
      }
    }
    
    function revert() {
      isActive = false;
    }
    
    function someFun() {
      alert('doubleclick detected');
    }