Keep mouse inside a div
Asked Answered
W

9

9

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?

Wilful answered 20/4, 2011 at 12:38 Comment(3)
You can't move the cursor or stop the cursor with JS so perhaps this isn't possible.Ochone
This question is almost 5 years ago, is there any updated solution?Dustindustman
@MahdiAlkhatib - as suggested by Calum, it is not possible max we can control the inner div position if it moves out of outer divWilful
B
3

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>
Bertina answered 20/4, 2011 at 13:16 Comment(1)
As of 2019 there is the Point Lock API: developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_APIZipah
O
4

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

Outwit answered 20/4, 2011 at 12:40 Comment(2)
nice link and nice suggestion by our SO mate, but cant do that here :(Wilful
This question is almost 5 years ago, is there any updated solution?Dustindustman
O
3

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>
Overtrump answered 20/4, 2011 at 12:48 Comment(4)
yes!! yes!! yes!! i want something like that only... any idea how to achieve this in js???Wilful
Sure: download the jQuery UI draggable behaviour by going to jqueryui.com/download, clicking "Deselect all components" and then selecting the "Draggable" Interaction, and click "Download". This will give you the smallest jQuery UI package with the required functionality. Then go back to the demo I mentioned and click "View Source" to see the sample code that using this library achieves what you need.Overtrump
You will need to include 2 js files from the zip in your page (js\jquery-1.5.1.min.js and js\jquery-ui-1.8.11.custom.min.js).Overtrump
I have added some snippets of js and html to the my answer to guide you. Note that including a big lib as jQuery UI in your page just for this effect is not very encouraging but I have a feeling you will be using a lot more from it from now on.Overtrump
B
3

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>
Bertina answered 20/4, 2011 at 13:16 Comment(1)
As of 2019 there is the Point Lock API: developer.mozilla.org/en-US/docs/Web/API/Pointer_Lock_APIZipah
R
1

if you want a creative solution, heres one that youl find very creative:

1: use [element].requestPointerLock()
2: create a new image of a mouse cursor. (here's one you might like)
3: create 2 new variables x and y, and lock the image position to them.
4: write:

document.addEventListener('mousemove', function(){
     x += window.movementX;
     y += window.movementY;
});

5: enter some if statements to keep the mouse image inside the element. make sure to keep the if statements' inside the eventlistener above:

document.addEventListener('mousemove', function(){
     x += window.movementX;
     y += window.movementY;

     if(x < parseFloat(element.style.left)){
            x = parseFloat(element.style.width);
     }
     if(x > parseFloat(element.style.left) + parseFloat(element.style.width)){
            x = parseFloat(element.style.width) + parseFloat(element.style.width);
     }
     if(y < parseFloat(element.style.top)){
            y = parseFloat(element.style.top);
     }
     if(y > parseFloat(element.style.top) + parseFloat(element.style.height)){
            y = parseFloat(element.style.top) + parseFloat(element.style.height);
     }
});

make sure to replace "element" with the name of the variable storing your element if you intend on using this exact code.

and dont forget to update the position of your element by assigning x and y to its position every time you use it. try the code below. it has all these steps implemented and tested. just click the screen to start, and press [Esc] to turn it off.

<style>
  cursor: none;
</style>
    <!DOCTYPE html>
    <html>
        <head>
            <meta charset="utf-8">
            <title>New webpage</title>
        </head>
        <body>
            <img id="div" src="https://lh3.googleusercontent.com/proxy/-3xjuhfpWxL0kfTWr6B2ZGmIKt7xWJ4d-3XcKg4m3wO4sMEen9cg_euf2xlkxwIrSbzQ0lOkDcUUI8TjEV172KVSPshQta9-Stql5WtHpzwkFrHQOY8X2S_PCEHg6GYJW6Zjr6PJeeFBNnLwdiAtB4XpWQ" alt="hi"     style="position: absolute; width: 20px; height: 20px;">
        
            <div id="cage" style="width: 200px; height: 200px; background-    color: lightgray; left: 0px; top: 0px;">
            
            
            </div>

	    <h1 id="tx">click to start</h1>
            
            
        </body>
        <script>
            var d = document.getElementById('div');
            var tx = document.getElementById('tx');
                document.addEventListener('click', function(){
    var txt = tx.textContent;
		    if(txt === "click to start"){
                		d.requestPointerLock();
		    	tx.textContent = "click to stop";
	    	}
		    if(txt === "click to stop"){
		    	document.exitPointerLock();  
		    	tx.textContent = "click to start";
            }    
	    });
        
            var x = 0;
            var y = 0;
        

            var cage = document.getElementById('cage');
        
            document.addEventListener("mousemove", function(e){
                x += e.movementX;
                y += e.movementY;
            
                if(x < parseFloat(cage.style.left)){
                    x = parseFloat(cage.style.left);
                }
                if(x > parseFloat(cage.style.left) +         parseFloat(cage.style.width)){
                    x = parseFloat(cage.style.left) + parseFloat(cage.style.width);
                }
                if(y < parseFloat(cage.style.top)){
                    y = parseFloat(cage.style.top);
                }
                if(y > parseFloat(cage.style.top) + parseFloat(cage.style.height)){
                    y = parseFloat(cage.style.top) + parseFloat(cage.style.height);
                }
                d.style.left = x + 'px';
                d.style.top = y + 'px';
            
            });

        </script>
    </html>
Region answered 16/8, 2019 at 19:34 Comment(0)
O
0

you can't control the mouse position with javascript, the only thing you can do is to read the mouse position and react to it. Maybe you can move the div so that it's always under the mouse?

Orjonikidze answered 20/4, 2011 at 12:40 Comment(1)
lol, this would be an amazing work around though. Imagine you're placing an object on a map and if you scroll out with the object the map chases you!Milano
F
0

You cannot constrain the mouse.

But if you want to constrain another object (for instance, one that is being dragged by the mouse) you can. But you will need to provide more info on what and how you try to do..

Four answered 20/4, 2011 at 12:42 Comment(0)
G
0

That's completely impossible, and you should be grateful for it. Your mouse is your system's primary input, and if browsers were able to control or commandeer it there is virtually nothing a site couldn't do.

It is possible, however, to constrain a dragged object within another DIV - jQueryUI's draggable(), for instance, makes this incredibly easy.

Gladiolus answered 20/4, 2011 at 12:42 Comment(0)
P
0

I seem to have found a workaround for my project.

I did the following:
1. Using CSS, disable the default click event of every element in your document.
2. For the body: cursor:none;.
3. Have a position:fixed; div function as a pseudo mouse.
4. Use jQuery to track mouse velocity and thus poisition your pseudo mouse.
5. Work from there.

Warning: Your real mouse will still function normally outside your webpage. My purpose did not require clicking any element and thus worked.

Perl answered 24/9, 2016 at 7:26 Comment(0)
M
0

I'm seeking for similiar solution on how to restrict mouse on my document view only but no luck since it isn't possible. So i just made a tweak on a script from w3schools movable div so i can restrict my element to my document view.

Here's my code:

dragElement(document.querySelector(".movable"));

	function dragElement(elmnt) {
		var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
		elmnt.onmousedown = dragMouseDown;

		function dragMouseDown(e) {
			e = e || window.event;
			e.preventDefault();
			pos3 = e.clientX;
			pos4 = e.clientY;
			document.onmouseup = closeDragElement;
			document.onmousemove = elementDrag;
		}

		function elementDrag(e) {
			e = e || window.event;
			e.preventDefault();
			pos1 = pos3 - e.clientX;
			pos2 = pos4 - e.clientY;
			pos3 = e.clientX;
			pos4 = e.clientY;
			elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
			elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
			if((elmnt.offsetTop - pos2) < 0) {
				elmnt.style.top = "0px";
			}
			if((elmnt.offsetLeft - pos1) < 0) {
				elmnt.style.left = "0px";
			}
			if(((elmnt.offsetTop - pos2) + elmnt.getBoundingClientRect().height) > window.innerHeight) {
				elmnt.style.top = (window.innerHeight - elmnt.getBoundingClientRect().height) + "px";
			}
			if(((elmnt.offsetLeft - pos1) + elmnt.getBoundingClientRect().width) > window.innerWidth) {
				elmnt.style.left = (window.innerWidth - elmnt.getBoundingClientRect().width) + "px";
			}
		}

		function closeDragElement() {
			document.onmouseup = null;
			document.onmousemove = null;
		}
	}
table.movable {
				position: fixed;
				z-index: 999;
				background-color: #f1f1f1;
				text-align: center;
			}

			table.movable thead > tr:nth-of-type(2) > th,
			table.movable tbody > tr > td {
				font-size: 13px;
			}

			table.movable .header {
				padding: 5px 10px;
				cursor: move;
				background-color: #3C4044;
				color: #fff;
			}

			table.movable tr:nth-of-type(2) > th {
				background-color: #3C4044;
				color: #fff;
			}
<table class="movable" width="300" border="2">
			<thead>
				<tr>
					<th colspan="3" class="header">Header</th>
				</tr>
				<tr>
					<th width="100">Sub-header 1</th>
					<th width="100">Sub-header 2</th>
					<th width="100">Sub-header 3</th>
				</tr>
			</thead>
			<tbody>
				<tr>
					<td>1</td>
					<td>2</td>
					<td>3</td>
				</tr>
			</tbody>
		</table>
Malti answered 10/2, 2020 at 8:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.