<ul>
<li><b>mousedown</b> to bring a rectangle to front and start dragging</li>
<li><b>click</b> to select a rectangle</li>
<li><b>dblclick</b> to edit a rectangle</li>
</ul>
<svg id="container" width="500" height="400">
<text x="50" y="50" fill="blue">test1</text>
<text x="100" y="100" fill="green">test2</text>
</svg>
CSS
.selected {
stroke: red;
stroke-width: 3;
}
JavaScript
var container = document.getElementById('container');
container.addEventListener('mousedown', function(evt) {
const rect = evt.target;
if (rect === container) return;
// bring <rect> to front and start dragging
// This re-attach the element and break the click and dbclick
// Try to comment this out.
container.appendChild(rect);
const dx = evt.offsetX - parseFloat(rect.getAttribute('x'));
const dy = evt.offsetY - parseFloat(rect.getAttribute('y'));
function onMousemove(evt) {
rect.setAttribute('x', evt.offsetX - dx);
rect.setAttribute('y', evt.offsetY - dy);
}
function onMouseup(evt) {
document.removeEventListener('mousemove', onMousemove, false);
document.removeEventListener('mouseup', onMouseup, false);
}
document.addEventListener('mousemove', onMousemove, false);
document.addEventListener('mouseup', onMouseup, false);
}, false);
container.addEventListener('click', function(evt) {
const rect = evt.target;
if (rect === container) return;
// select/highlight the <rect>
container.querySelectorAll('.selected').forEach(node => node.classList.remove('selected'));
rect.classList.add('selected');
});
container.addEventListener('dblclick', function(evt) {
const rect = evt.target;
if (rect === container) return;
// edit the <rect> / change its color
rect.setAttribute('fill', `#${Math.floor(Math.random()*16777215).toString(16)}`);
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.