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?

Sam Holder
  • 32,535
  • 13
  • 101
  • 181
Varun
  • 5,001
  • 12
  • 54
  • 85

9 Answers9

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

Community
  • 1
  • 1
Jim Blackler
  • 22,946
  • 12
  • 85
  • 101
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>
JJJ
  • 32,902
  • 20
  • 89
  • 102
miguelv
  • 2,856
  • 1
  • 25
  • 24
  • yes!! yes!! yes!! i want something like that only... any idea how to achieve this in js??? – Varun Apr 20 '11 at 13:13
  • Sure: download the jQuery UI draggable behaviour by going to http://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. – miguelv Apr 20 '11 at 13:57
  • 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). – miguelv Apr 20 '11 at 14:00
  • 1
    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. – miguelv Apr 20 '11 at 14:06
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>
Liam
  • 27,717
  • 28
  • 128
  • 190
Elieder
  • 141
  • 1
  • 7
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>
person the human
  • 345
  • 4
  • 15
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.

Ryan Dsouza
  • 103
  • 1
  • 7
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?

Florian
  • 3,145
  • 1
  • 27
  • 38
  • 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! – Shaded Apr 20 '11 at 12:49
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..

Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
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.

Winfield Trail
  • 5,535
  • 2
  • 27
  • 43
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>