views:

102

answers:

1

Hello, i need to implement mouse resistance in javascript.

As an example of what i mean, think of how the Enligthenment window manager handles screen edge resistance to switch between different desktops, or if you are not familiar with that:

imagine a large rectangle with a square within it. when click-moving the mouse [onmousedown] within the square, the mouse lets itself be moved until the borders of the square, then exercises some resitance until a threshold is met, and then moves around within the larger rectangle.

Ideally the mouse cursor should stay trapped within the square until that threshold isnt met, and only leave that area if it is met.

Any ideas or examples of this somewhere? A crossbrowser solution is also greatly appreciated. (down to ie7, that is) Thanks!

+2  A: 

As stated you can't set the mouse position with Javascript.

Since you asked about implementing this on mousedown, however, I assume the user is dragging something around on screen. So you could have the element they are dragging show this behavior. You need two elements to act as regions, one where the target can be freely dragged and another to define the size of the boundary. I'd do it with jQuery to shorten up the code but basically you'd have something like this. (Untested code)

HTML:

<div class='borderLand'>
    <div class='freeZone'>
        <img class='draggable'>
    </div>
</div>

CSS:

.borderLand {position: relative; width: 110px; height: 110px;}
.freeZone {position: relative; top: 10px; left:10px; height: 100px; width: 100px;}

JS:

I can't write the full code off the top of my head but the algorithm would be something like

onmousedown{
  check for click location
  if it's over the draggable (watch for bubbling) begin dragging, set dragging flag
}

onmouseup{
  clear dragging flag if it's set
}

borderland onmouseover{
  if dragging, stop the movement of the draggable (watch for bubbling here too)
}

borderland onmouseout{
  start dragging again (if they move back in or out it doesn't matter, you want to drag)
}

Sorry if you need more detail, but doing this in plain JS would be a little lengthy and I'm not sure how much help you need.

T. Markle