Cancel click event in the mouseup event handler

前端 未结 14 2417
梦毁少年i
梦毁少年i 2020-12-09 14:53

Writing some drag&drop code, I\'d like to cancel the click events in my mouseup handler. I figured preventing default should do the trick, but the click event is still f

相关标签:
14条回答
  • My solution doesn't require global variables or timeouts or changing html elements just jquery which surely has some aquivalent in plain js.

    I declare a function for onClick

    function onMouseClick(event){
         // do sth
    }
    

    I declare a function for MouseDown (u may also do the same in mouse up) to decide if to handle an onclick event or not

    function onMouseDown(event){
         // some code to decide if I want a click to occur after mouseup or not
        if(myDecision){
            $('#domElement').on("click", onMouseClick);
        }
        else $('#domElement').off("click");
    } 
    

    Quick Note: you should make sure that
    $('#domElement').on("click", onMouseClick); is not executed multiple times. Seems to me that in case it is the onMouseClick will be called multiple times too.

    0 讨论(0)
  • 2020-12-09 15:44

    The best solution for my situation was:

    let clickTime;
    
    el.addEventListener('mousedown', (event) => {
      clickTime = new Date();
    });
    
    el.addEventListener('click', (event) => {
      if (new Date() - clickTime < 150) {
        // click
      } else {
        // pause
      }
    });
    

    This gives the user 150ms to release, if they take longer than 150ms it's considered a pause, rather than a click

    0 讨论(0)
提交回复
热议问题