I have 3 SVG rect objects. I want to move them with the mouse. The problem is that I can only move when I create the object dynamically in the JavaScript code. If I create in HTML within SVG, I can not move. Example:
I have 3 SVG rect objects. I want to move them with the mouse. The problem is that I can only move when I create the object dynamically in the JavaScript code. If I create in HTML within SVG, I can not move. Example:
Your code is only adding an event handler to the circle
element, you must adapt it to the rect
elements as well.
You can do it like this:
var rects = document.querySelectorAll('rect');
for (var i = 0; i < rects.length; i++) {
rects[i].addEventListener('mousedown', mousedown);
}
shape.addEventListener('mousedown', mousedown);
(or you could use delegation as in the example at the end of the response)
Then you have to solve another problem, the co-ed. In the setter and getter elements since rect
has x
and y
, but circle
elements have cx
and cy
.
Here's a suggestion:
function mousedown(evt) {
var evt = evt || window.event;
ddData.element = this;
ddData.initialX = evt.clientX;
ddData.initialY = evt.clientY;
ddData.originalX = parseFloat(ddData.element.getAttributeNS(null, this.tagName == 'rect' ? 'x' : 'cx'));
ddData.originalY = parseFloat(ddData.element.getAttributeNS(null, this.tagName == 'rect' ? 'y' : "cy"));
};
svg.onmousemove = function (evt) {
var evt = evt || window.event;
var el = ddData.element;
if (el) {
var posX = ddData.originalX + evt.clientX - ddData.initialX;
var posY = ddData.originalY + evt.clientY - ddData.initialY;
if (el.tagName == 'rect') {
//move object
el.setAttributeNS(null, "x", posX);
el.setAttributeNS(null, "y", posY);
} else {
el.setAttributeNS(null, "cx", posX);
el.setAttributeNS(null, "cy", posY);
}
}
}
You can even do this with delegation (via event.target
) and you do not even need the for
cycle. In this example I use .id
to decide whether the element can be moved or not (assuming elements with ID can be moved), but you could do this with a class or data-
field.