SVG – Click and Drag/Move Object With Mouse/Cursor

I’m working with SVG graphics and JavaScript right now. I was trying to find out how to do something seemingly very simple… click and drag an object to move it. What I found, however, was very little. The few examples I found either relied on a 3rd party libraries, or had examples using standard JS but didn’t work correctly. So, I worked on this for a bit and came up with a solution using basic JS code that functions well.

The main glitch that I saw in other examples is while dragging an object, if your cursor gets too far away from the object, the object being moved behaves erratically. The reason is because the script uses mouse events to determine when to start/stop moving an object. The event onmouseup is used to detect when the user stops moving the object. However, in the previously mentioned glitch, if the mouse is no longer positioned about the object, the script wont be able to detect when the onmouseup event actually occurs.

To fix this, I added in detection for one additional mouse event: onmouseout. This will detect when the cursor has “left” the object. So if either event occurs (onmouseup or onmouseout) the object move is stopped.

View the example here: Click and Drag SVG example

Here is the code for the JavaScript and SVG: