Elaine
Elaine

Reputation:

jQuery dragging divs selected text

I'm using jquery to make a few divs draggable on a website. My code is similar to this:

$("#thediv").bind('mousedown',function(){
    $(document).bind('mousemove',function(ms){
      //drag
    })
});

The problem is that if the mouse is too fast for the div, the mouse goes outside of the div. This selects random content on the screen (highlights it blue). It does not give a smooth drag effect. Is there a nice way of fixing this? jQuery's ui drag plugin does not have this problem. I don't want to use it though because it is a large file.

Thanks

Upvotes: 1

Views: 2713

Answers (2)

Jason
Jason

Reputation: 3485

Also consider CSS:

#thediv {
    -webkit-user-select: none;
    -khtml-user-select: none;
    -moz-user-select: none;
    -o-user-select: none;
    user-select: none;
}

Upvotes: 1

Anatoliy
Anatoliy

Reputation: 30073

To prevent selection of elements in page just return false from your functions (onmousedown, onmousemove). Also for this functionality you do not need jquery, simply use this pattern:

var mouseMove = function () {
    // move div
    return false;
}
var mouseUp = function () {
    document.onmousemove = null;
    document.onmouseup = null;          
}
var mouseDown = function () {
    document.onmousemove = mouseMove;
    document.onmouseup = mouseUp;
    return false;
}
div.onmousedown = mouseDown;

Don't forget return false from event function mouseMove to prevent default events;

Upvotes: 4

Related Questions