George Reith
George Reith

Reputation: 13476

jQuery making element move with mouse

So I can make an element move with the mouse, however the problem is the offset is calculated from the top left corner of the element and doesn't take into account the mouse's position within the element causing the object to leap towards the mouse and preventing you from dragging it upwards or left.

So I came up with this function:

  handle.on("mousemove", function(e) {
    if (state.dragging) {
      var paneOffset = pane.offset();
      var mouseOffset = {
        'top': e.pageY - paneOffset.top,
        'left': e.pageX - paneOffset.left
      }
      pane.offset({
        top: e.pageY - mouseOffset.top,
        left: e.pageX - mouseOffset.left
      });
    }
  });

Example: http://jsfiddle.net/SEKxc/

The problem with this is it stops the element from moving as it always calculates the element's same exact offset. How would I make the element follow the mouse but relative to the mouse's position with the object.

I am aware of jQueryUI having this functionality built-in but don't want to use that.

Upvotes: 1

Views: 996

Answers (2)

user1941493
user1941493

Reputation:

You could calculate the initial mouseoffset on dragstart and hence use it as a global variable from within the mousemove handler. Since the dragstart starts before mouse move i dont see a problem.

Update: you need to store both the objects initial offset and the mouses initial offset and calculate the relative offset of the mouse compared to the original on mouseMove then apply the same transformation to the element.

Upvotes: 1

Guffa
Guffa

Reputation: 700192

Store the distance between the mouse position and the element top left corner when you start dragging. Then you just subtract those from the mouse position to calculate the element position when the mouse moves.

Upvotes: 0

Related Questions