Reputation: 23
Is it possible to restrict text selection to single tags? When using absolute position, texts seem to be marked across multiple elements, e.g. in the following example:
<span style="position: absolute; left: 171px;"><span>TextBlock</span></span>
<div style="position: absolute; left: 0px;">
<input type="radio"></input><label>RadioButton</label>
</div>
<div style="position: absolute; left: 607px; top: 100px">
<input type="radio"></input><label>RadioButton</label>
</div>
If you double-click the text of one of the controls, those text of previously added items are selected as well. Is there any way to restrict this? And this excludes disabling selection completely since it is a must-have feature.
I also tried user-select (specifically the webkit-version for Chrome) but unfortunately to no avail.
Upvotes: 1
Views: 103
Reputation: 26
You can use javascript to solve this.
function selectElement(element) {
var selection,
range;
if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') {
element.focus();
element.setSelectionRange(0, element.value.length);
} else {
if (element.hasAttribute('contenteditable')) {
element.focus();
}
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(element);
selection.removeAllRanges();
selection.addRange(range);
}
}
function getSelectElementCallback(element) {
return function () {
selectElement(element);
};
}
var elements = document.getElementsByClassName('select-only-this');
for (var i = 0, l = elements.length; i < l; i++) {
elements[i].addEventListener('dblclick', getSelectElementCallback(elements[i]));
}
Here is a rapid fiddle that do what you want.
Upvotes: 1
Reputation: 1597
Using user-select
you should disable selection only for some elements, allowing the normal selection on the rest of the document. In this pen with similar content of your example, I used the class no-selection
to apply in those element.
user-select
have a great browsers support
Upvotes: 0