Reputation: 19719
Let's say I have a set of contenteditable="true"
divs.
<div id="0" contenteditable="true"></div>
<div id="1" contenteditable..></div>
<div...etc></div>
I can't have one div, multiple divs is a must. How could I highlight the content of more than one div? Using ranges? Anything else?
Upvotes: 7
Views: 6978
Reputation: 611
Another solution is to turn on the contentaditable
of the parent element instead of turning it off on each child.
const editableDivs = document.getElementsByClassName("editable")
let selecting = false
for (const editableDiv of editableDivs) {
editableDiv.addEventListener("mouseleave", (event) => {
if (selecting)
document.body.setAttribute("contenteditable", "true")
})
}
document.body.addEventListener("mousedown", (event) => {
selecting = true
})
document.body.addEventListener("mouseup", (event) => {
document.body.setAttribute("contenteditable", "false")
selecting = false
})
<div class="editable" contenteditable="true">
This is the first editable div.
</div>
<div class="editable" contenteditable="true">
This is the second editable div.
</div>
Upvotes: 0
Reputation: 6431
It is possible to switch the divs to contenteditable="false"
on the fly as a consequence of starting a selection in one of them. Something like this gives you the idea (using JQuery):
$('div').bind("selectstart", function() {
$('div').attr("contenteditable", false);
});
Here's a fiddle to demonstrate (only tested in Chrome).
Note in the fiddle example that the first ContentEditable Div gets the focus. This allows you to type away as normal, but as soon as you select anything, using mouse or keyboard, you'll see you can extend the selection across divs as usual.
This obviously needs fleshing out to work with multiple browsers and to turn back to contenteditable="true"
appropriately. But I think the approach is valid.
Upvotes: 5
Reputation: 324567
The answer is that it depends on the browser. See this example for a test of two methods using Ranges. The first attempts to create a Range per editable <div>
and add all of them to the selection. The second attempts to create a single Range encompassing the contents of two editable <div>
s.
Results:
Selection
API as other browsers, but the equivalent TextRange
code does not allow selection from more than one editable element.Upvotes: 8