user701510
user701510

Reputation: 5763

Making my own "draggable" function

It seems that my attempt at trying to replicate Jquery UI's draggable function has proven the Quantum Mechanics principle of a div existing in two places at once.

When I hold my mouse down on the box div and move the mouse cursor, the box div starts flashing like crazy and a "clone" of the box div appears to the southeast of the original box div and it is also flashing.

Here's the jsfiddle:

jsfiddle

Upvotes: 5

Views: 239

Answers (2)

Sal
Sal

Reputation: 1655

I have fixed your jsfiddle, give it a go now: http://jsfiddle.net/5Sxrq/2/

The issues were:

margin-top:100px;
margin-left:80px;

if you want to use margins then you'll have to subtract it from offsets

boxOff = $('#box').offset();
mouseOffX = e.pageX - boxOff.left;
mouseOffY = e.pageY - boxOff.top;

You should get mouseOffX and mouseOffY when mousedown event was called, not every time with mousemove

EDIT: this one is with fixed margin issues: http://jsfiddle.net/5Sxrq/3/

Upvotes: 7

Tikhon Jelvis
Tikhon Jelvis

Reputation: 68152

The reason you get flickering is that you're calculating the offset of the mouse within the box each time the mouse moves. If you just calculate mouseOffX and mouseOffY once in onmousedown, you won't have it flicker.

Here is a modified version. It still has some issues, but no flickering: http://jsfiddle.net/RzqQE/

I'm going to try to fix the weird offset thing in my version, but I can't give you any guarantees--I'm liable to fall asleep at any moment.

Edit: Ah, fixed it. Here's a version that works: http://jsfiddle.net/7QzZM/

Now to explain what I did:

We don't really care about the position of the mouse in the block. What we care about is how much to move the block each time the mouse moves. We can figure this out by getting the deltas of the mouse's position (dx and dy in my code). To get the block's new position, we just add the deltas to its old position.

The other difference was that I used $('#box').position() instead of $('#box').offset(); this returns the position relative to the box's parent rather than relative to the document.

Upvotes: 5

Related Questions