Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS - how to get the text between the beginning of the node and current caret (text cursor) position?

I need to get the text (or the whole inner html) of a node, truncated on current caret (text cursor) position in an element with contenteditable set to true. I've tried using range.setStart() etc, but I can't make heads and tails of it...

Edit: For clarification, upon some events I want the script to extract text from the beginning of the node that currently has focus to the caret's position (where the blinking vertcal line currently is if an editable field has focus) and store it in a variable. Action similar to what would happen if a user pressed ctrl+shift+home and ctrl+c

Example: Given html:

<span contenteditable=true>Hello, world<br> Good bye, World</span>

And assuming that the caret is between "Good" and "bye", I'd like to retrieve

"Hello, world<br> Good"

like image 416
Kuba Orlik Avatar asked Dec 12 '22 15:12

Kuba Orlik


1 Answers

I would suggest the following approach:

  • create a range encompassing the content you want
  • call the range's cloneContents() method to obtain a DocumentFragment representing the range's content
  • create a <div> or <body> element and append the fragment to it
  • get the element's innerHTML

Example: http://jsfiddle.net/sUSYG/

Code:

function getHtmlPrecedingSelectionIn(container) {
    var html = "";
    if (window.getSelection && document.createRange) {
        var sel = window.getSelection();
        if (sel.rangeCount > 0) {
            var selRange = sel.getRangeAt(0);
            var range = document.createRange();
            range.selectNodeContents(container);
            range.setEnd(selRange.startContainer, selRange.startOffset);

            var frag = range.cloneContents();
            var el = document.createElement("body");
            el.appendChild(frag);
            html = el.innerHTML;
        }
    }
    return html;
}

Caveats:

  • this won't work in IE <= 8, although it's not too hard to do (either by coding something using its different selection/range API or by using a library such as Rangy)
  • the HTML produced is not guaranteed to be a substring of the original HTML of the editable span.
like image 123
Tim Down Avatar answered Apr 19 '23 06:04

Tim Down