Search code examples
javascriptjqueryeventsmouseeventmouseup

Is there a way to trigger mouseup when leaving the document body?


I found some code and I made a jsfillde with it. I need to know how to trigger mouseup in the function below, when you leave document body (in the fiddle example it's like dragging the object into HTML section for instance and leave the mouse click there).

function handleMouseMove(e) {
    if (canMove) {
        var left = getMousePosX(e);
        var top = getMousePosY(e);
        var newLeft = ($(elemToMove).css('left').toDecNum() + (left - lastPosX));
        var newTop = ($(elemToMove).css('top').toDecNum() + (top - lastPosY));

        $(elemToMove).css('left', newLeft);
        $(elemToMove).css('top', newTop);
        lastPosX = left;
        lastPosY = top;
    }

    return false;
}

Thanks for any suggestion.


Solution

  • You can use

    document.onmouseout = handleMouseUp;
    

    This says that when the mouse leaves the document object, the handleMouseUp handler should be called.

    Updated fiddle: http://jsfiddle.net/vp14utt1/1/

    -

    P.S. for event handlers that simply take the event as an argument, you can just use the function name without wrapping it.

    document.onmousedown = function (e) { handleMouseDown(e); };
    document.onmousedown = handleMouseDown;