I have an SVG element in which I have made a foreignObject. The foreignObject contains two objects a textarea and a div. The textarea lies on top of the div and is transparent. When people type in the textarea the text is copied to the div (a WYSIWYG kind of editor). This all works fine. The problem is however: when you select text in the textarea (which is 100% transparent) you can’t see what text you have selected and so now I want to create a code which copies the selection to the text in the div.
I have the following to bits, this bits tells me what is selected in the textarea:
var start = e.target.selectionStart;
var end = e.target.selectionEnd;
(e is the event of a select eventlistener)
and the following selects the text in the div:
div = $(e.target).next('div');
div = div[0];
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(div);
selection.addRange(range);
This works, but selects all text in the div. How do I constrain the selection to only the part selected in the textarea?
(by the way this code is for a demo-application and only needs to work in firefox)
I had a similar problem. My solution was to add two empty HTML elements (maybe
<span class="sel-start"/>and<span class="sel-end"/>) to the outputdivwhile doing the conversion.You can use the same trick to show a text cursor in the
div, so it’s easier for users to see where they are right now. Plus you can use the text cursor to scroll thedivso it wastes less screen space.It’s simple to select those and they cut the text into segments which you can easily wrap in
<span class="selected">...</span>elements to style them.Note that it’s not smart to use a single
spanbecause the selection might span block elements (p,div, lists, tables).