Search code examples
javascriptjqueryclickjquery-eventsmouseup

Cancel click event in the mouseup event handler


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 fired.

Is there a way to do this?


This doesn't work:

<div id="test">test</div>
<script>
$("#test").mouseup (function (e) {
  var a = 1;
  e.preventDefault();
});
$("#test").click (function (e) {
  var a = 2;
});

Solution

  • I had the same problem and didn't found a solution either. But I came up with a hack that seems to work.

    Since the onMouseUp handler doesn't seem to be able to cancel the click on a link with preventDefault or stopEvent or anything, we need to make the link cancel itself. This can be done by writing an onclick attribute which returns false to the a-tag when the drag begins, and removing it when the drag ends.

    And since the onDragEnd or onMouseUp handlers are run before the click is interpreted by the browser, we need to do some checking where the drag ends and which link is clicked and so on. If it ends outside the dragged link (we dragged the link so that the cursor isn't on the link anymore), we remove the onclick handler in the onDragEnd; but if it ends where the cursor is on the dragged link (a click would be initiated), we let the onclick-handler remove itself. Complicated enough, right?

    NOT COMPLETE CODE, but just to show you the idea:

    // event handler that runs when the drag is initiated
    function onDragStart (args) {
      // get the dragged element
      // do some checking if it's a link etc
      // store it in global var or smth
    
      // write the onclick handler to link element
      linkElement.writeAttribute('onclick', 'removeClickHandler(this); return false;');
    }
    
    // run from the onclick handler in the a-tag when the onMouseUp occurs on the link
    function removeClickHandler (element) {
      // remove click handler from self
      element.writeAttribute('onclick', null);
    }
    
    // event handler that runs when the drag ends
    function onDragEnds (args) {
      // get the target element
    
      // check that it's not the a-tag which we're dragging,
      // since we want the onclick handler to take care of that case
      if (targetElement !== linkElement) {
        // remove the onclick handler
        linkElement.writeAttribute('onclick', null);
      }
    }
    

    I hope this gives you an idea of how this can be accomplished. As I said, this is not a complete solution, just explaining the concept.