Keep mouse inside a div

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 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>

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>