Avoid click event on mouse move

Often enough, especially when dragging stuff around, you want to avoid triggering the click event after releasing the mouse. Since browsers don't do this natively, here's a simple solution

HTML

<p>open your console and click on the boxes. If you press your mouse button and move the mouse before you release it, the click event should be aborted</p>

<div class="delegated">delegated mouse move click stopper</div>
<div class="bound">bound mouse move click stopper</div>

CSS

p {
    margin-bottom: 10px;
}
div {
    width: 400px;
    height: 100px;
    background: #DDD;
    margin-bottom: 10px;
}

JavaScript

// mouse move click prevent
(function($){
    var $doc = $(document),
        moved = false,
        pos = {x: null, y: null},
        abs = Math.abs,
        mclick = {
        'mousedown.mclick': function(e) {
            pos.x = e.pageX;
            pos.y = e.pageY;
            moved = false;
        },
        'mouseup.mclick': function(e) {
            moved = abs(pos.x - e.pageX) > $.clickMouseMoved.threshold
                || abs(pos.y - e.pageY) > $.clickMouseMoved.threshold;
        }
    };
    
    $doc.on(mclick);
    
    $.clickMouseMoved = function () {
        return moved;
    };
    
    $.clickMouseMoved.threshold = 3;
})(jQuery);


// test delegated
$(document).on('click', '.delegated', function(e) {
    if ($.clickMouseMoved()) {
        console.log('click aborted');
        return;            
    }
    console.log('click');
});