Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
January 2, 2022 11:30 am GMT

Drag and drop SVG elements

In this article we will drag and drop SVG elements.

Lets build a site.
Lets add an SVG with two rectangles.
Lets add the CSS class to check if the element is draggable.

Add a mousedown event listener for the SVG-element.
First, check if the element has the draggable class name.
If so, get the mouse position.
Remember the element we start to drag and its position.
Then start to listen to mousemove events.

On mouse move we get the current mouse position
and we change the element position.
So the element is dragging.

When the mouse button is up we stop to listen to mouse move events.
So the element is dropped.

Lets check it out.

Drag the rectangle. Drop it.
Drag another one. Drop it.
It works! :)

const svg = document.getElementById('svg');let startX, startY, elementX, elementY, element;svg.addEventListener('mousedown', e => {    const className = e.target.getAttributeNS(null, 'class');    if (className.indexOf('draggable') >= 0) {        startX = e.offsetX;        startY = e.offsetY;        element = e.target;        elementX = +element.getAttributeNS(null, 'x');        elementY = +element.getAttributeNS(null, 'y');        svg.addEventListener('mousemove', onMouseMove);    } }); onMouseMove = e => {    let x = e.offsetX;    let y = e.offsetY;    element.setAttributeNS(null, 'x', elementX + x - startX);    element.setAttributeNS(null, 'y', elementY + y - startY); }; svg.addEventListener('mouseup', e => {    svg.removeEventListener('mousemove', onMouseMove); });

I hope you found this article useful, if you need any help please let me know in the comment section.

See you next time. Have a nice day!

Subscribe to our channel:
https://www.youtube.com/c/Samovar101


Original Link: https://dev.to/101samovar/drag-and-drop-svg-elements-3oif

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To