Search code examples
javascriptjqueryonclickmousedownmouseup

Prevent Click Event When Dragging Using Mouseup/Down


I'm using a mousedown/mouseup solution for click and drag navigation but if hovering over a link and dragging it fires the link when the click is released.

How can I disable the click function when dragging?

Here's what I've got:

jQuery(document).ready(function($) {

   $(".main-container").mousedown(function(e) {
       e.preventDefault();
       down = true;
       x = e.pageX;
       y = e.pageY;
       top = $(this).scrollTop();
       left = $(this).scrollLeft();
       $(event.toElement).one('click', function(e) {
       });
   });

   $("body").mousemove(function(e) {
       if (down) {
           var newX = e.pageX;
           var newY = e.pageY;

           //console.log(y+", "+newY+", "+top+", "+(top+(newY-y)));

           $(".main-container").scrollTop(top - newY + y);
           $(".main-container").scrollLeft(left - newX + x);
       }
   });

   $("body").mouseup(function(e) {
       down = false;
       $(event.toElement).one('click', function(e) {
       });
   });
});

Thanks


Solution

  • This seems to do the trick:

    jQuery(document).ready(function($) {
    
    var x, y, top, left, down;
    
    $(".main-container").mousedown(function(e) {
        e.preventDefault();
        down = true;
        x = e.pageX;
        y = e.pageY;
        top = $(this).scrollTop();
        left = $(this).scrollLeft();
        timestamp = new Date().getTime();
    });
    
    $("body").mousemove(function(e) {
        if (down) {
            var newX = e.pageX;
            var newY = e.pageY;
    
            $(".main-container").scrollTop(top - newY + y);
            $(".main-container").scrollLeft(left - newX + x);
        }
    });
    
    $("body").mouseup(function(e) {
        down = false;
    });
    
    $(".main-container").click(function(event) {
        var interval = 350;
        var timestamp2 = new Date().getTime();
        if ((timestamp2 - timestamp) > interval) {
            return false;
        }
    });
    
    });