Reputation: 4626
When I add a text node to my document it is sometimes selected/highlighted initially.
With the following code, when I click outside the red rect the text is added correctly (without being selected).
When I click inside the red rect the text appears selected. After clicking anywhere, the selection is removed and the text can no longer be selected.
Can anyone explain what is going on and how to fix this?
<html><body>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
<rect id="box" width="250" height="28" fill="none" stroke="white" pointer-events="visible"/>
</svg>
<script>
document.documentElement.addEventListener("click", foo);
function foo()
{
document.documentElement.removeEventListener("click", foo);
var t = document.createElementNS("http://www.w3.org/2000/svg", "text");
t.textContent = 'foo';
t.setAttribute('id', "text_");
t.setAttribute('x', 20);
t.setAttribute('y', 20);
// Make all text unselectable...across all browsers
t.setAttribute('style', '-webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;');
var box = document.getElementById('box');
box.parentNode.insertBefore(t, box);
//box.parentNode.appendChild(t); // no selection when using this..but I need the element on top
}
</script>
</body></html>
In case the moz tag doesn't give it away, I'm using Firefox.
A fiddle to demonstrate... https://jsfiddle.net/ncbxh73s/9/
Upvotes: 1
Views: 1511
Reputation: 124029
Here's a workaround.
document.documentElement.addEventListener("click", foo);
function foo()
{
document.documentElement.removeEventListener("click", foo);
var t = document.createElementNS("http://www.w3.org/2000/svg", "text");
t.textContent = 'foo';
t.setAttribute('id', "text_");
t.setAttribute('x', 20);
t.setAttribute('y', 20);
// Make all text unselectable...across all browsers
t.setAttribute('style', '-webkit-touch-callout: none;-webkit-user-select: none;-khtml-user-select: none;-moz-user-select: none;-ms-user-select: none;user-select: none;');
var box = document.getElementById('box');
box.parentNode.insertBefore(t, box);
document.querySelector('svg').deselectAll();
}
<html><body>
<svg version="1.1" xmlns="http://www.w3.org/2000/svg">
<rect id="box" width="250" height="28" fill="none" stroke="white" pointer-events="visible"/>
</svg>
</body></html>
Upvotes: 2