Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep mouse inside a div

I have a div of say 100px,100px dimensions, onmousedown I want to move an object inside this div and want the mouse should not point anywhere else except that div so that my object is placed in the div. Mouse will be back to normal onmouseup .

What should be the javascript to keep the mouse inside that div only?

like image 633
Varun Avatar asked Apr 20 '11 12:04

Varun


3 Answers

Impossible sadly... or happily if you think what some adverts might do with it.

Edit: found this discussion, where someone suggests a novel workaround Move Mouse Cursor Javascript

like image 145
Jim Blackler Avatar answered Nov 20 '22 10:11

Jim Blackler


It's not possible to control mouse position with Javascript; but you can take his position to control the object that you want... here a simple code that almost do this:

<html>
<body>
<div id="divID" style="width: 100px; height: 100px; position: absolute; left: 250px; top: 300px; background: #000"></div>
<div id="divChild" style="width: 20px; height: 20px; color: #f00; position: absolute; background: #f00;"></div>
</body>
<script>
var div = document.getElementById("divID");
var divChild = document.getElementById("divChild");

mousepressed = 0;

function handleMyMouseMove(e) {
    var mouseX = e.clientX;
    var mouseY = e.clientY;
    if(mousepressed) {
        divChild.style.left = mouseX + "px";
        divChild.style.top = mouseY + "px";
    }
}

function handleMyMouseDown(e) { mousepressed = 1; }
function handleMyMouseUp(e) { mousepressed = 0; }

div.addEventListener("mousemove", handleMyMouseMove, false);
div.addEventListener("mousedown", handleMyMouseDown, false);
window.addEventListener("mouseup", handleMyMouseUp, false);
</script>
</html>
like image 30
Elieder Avatar answered Nov 20 '22 09:11

Elieder


Like the other guys say you can't constraint the mouse cursor to a specific area. But maybe that is not what you want. Look at this jQuery UI demo: Constrain Movement. It achieves the desired effect by keeping the inner object inside the parent object (see box saying "I'm contained within my parent").

<div class="draggable ui-widget-content">
<p id="draggable5" class="ui-widget-header">I'm contained within my parent</p></div>

<script>
$(function() {
    $( "#draggable5" ).draggable({ containment: "parent" });
});
</script>
like image 3
miguelv Avatar answered Nov 20 '22 09:11

miguelv