1

I'm running an experiment to see if I can return that absolute start and end points of a highlighted block of test within a contentEditable (not actually important to the test) div. I'm not building a rich text editor or anything I just want to know how it's done! So all I want to return upon right click (not important, I'm just messing with that too) are two numbers, the absolute distance from the start of the wrapper div to the start of the selection and the absolute distance from the start of the wrapper div to the end of the selection.

I thought Mootools would make this easy but I could only get their implementation to work with forms (i.e. textarea, input etc). So I had a quick bash using Google, and it all worked fine when no tags were involved, e.g. He|llo Wor|ld (where the pipe, |, represents the highlighted range) would return [2, 9] which is correct. However, the moment I add tags to the div to allow colours / formatting these numbers do not make any sense as the range only gives position relative to text nodes and not an absolute value. Any ideas how to get this? I can only imagine it involves some form of horrendous DOM manipulation.

JS:

window.addEvent('domready', function()
    {
        document.body.addEvent('contextmenu', 
            function(e)
            {
                e.stop();
            }
        );

        if(!window.SelectionHandler)
        {
            SelectionHandler = {};
        }

        SelectionHandler.Selector = {};

        SelectionHandler.Selector.getSelected = function()
        {
            var userSelection = '';

            if(window.getSelection)
            {
                userSelection = window.getSelection();
            }
            else if(document.getSelection)
            {
                userSelection = document.getSelection();
            }
            else if(document.selection)
            {
                userSelection = document.selection.createRange();
            }

            return userSelection;
        }

        SelectionHandler.Selector.getText = function(userSelection)
        {
            var selectedText = userSelection;

            if(userSelection.text)
            {
                selectedText = userSelection.text;
            }

            return selectedText;
        }

        SelectionHandler.Selector.getRange = function(userSelection)
        {
            if(userSelection.getRangeAt && typeof(userSelection.getRangeAt) != 'undefined')
            {
                var selectedRange = userSelection.getRangeAt(0);
            }
            else
            {
                var selectedRange = document.createRange();
                selectedRange.setStart(userSelection.anchorNode, userSelection.anchorOffset);
                selectedRange.setEnd(userSelection.focusNode, userSelection.focusOffset);
            }

            return selectedRange;
        }

        $('mydiv').addEvent('mousedown', 
            function(event)
            {
                if(event.rightClick)
                {
                    var userSelection   = SelectionHandler.Selector.getSelected();
                    var selectedText    = SelectionHandler.Selector.getText(userSelection);
                    var selectedRange   = SelectionHandler.Selector.getRange(userSelection);

                    // New ranges to add identifiable nodes (must be in that order!?)
                    var endRange = document.createRange();
                    endRange.setStart(selectedRange.endContainer, selectedRange.endOffset);
                    endRange.insertNode(document.createTextNode('!~'));

                    var startRange = document.createRange();
                    startRange.setStart(selectedRange.startContainer, selectedRange.startOffset);
                    startRange.insertNode(document.createTextNode('~!'));

                    // Find the position of our new identifiable nodes (and account for their removal)
                    var div_content = $('mydiv').get('html');
                    var start       = div_content.indexOf('~!');
                    var end         = div_content.indexOf('!~') - 2;

                    // Remove our identifiable nodes (DOESN'T WORK)
                    //startRange.deleteContents();
                    //endRange.deleteContents();

                    // This does work, but obviously loses the selection
                    div_content = div_content.replace('~!', '').replace('!~', '');
                    $('mydiv').set('html', div_content);

                    console.log(start + ' vs ' + end);
                }
            }
        );
    }
);

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>Edit Range Test</title>
 </head>

 <script type="text/javascript" src="mootools.js"></script>
 <script type="text/javascript" src="edit_range.js"></script>

 <style>
    #mydiv {
        width: 400px;
        height: 400px;
        border: 1px solid #a2a2a2;
        padding: 5px;
    }
 </style>

 <body>
    <h1>Edit Range Test</h1>

    <div id="mydiv" contentEditable="true"><span style="color: red;">Hello</span> World! <span style="color: red;">Hello</span> World! </div>

 </body>
</html>

So when I now select He|llo Wor|ld (where the pipe, |, again represents the highlighted range) it would return [2, 4] when I want [28, 42].

EDIT: I've updated the code to clarify what I am trying to do. It does most of what I wanted to test, but loses the selection and is very scruffy!

Thanks in advance!

Paul Norman
  • 1,621
  • 1
  • 9
  • 20

1 Answers1

0

First, the information you get from Range objects are about as useful as you can get: for each of the start and end boundaries of the Range you get a DOM node and an offset within that node (a character offset inside a text or comment node or a child node offset otherwise), which completely describes the boundary. What you mean by "absolute start and end points" I imagine is two character offsets within the whole editable element, but that is a slippery concept: it seems simple, but is tricky to pin down. For example, how many characters does a paragraph break count for? A <br>? An <a> element with display: block? Elements such as <script> elements that contain text but are not visible to the user? Elements hidden via display: none? Elements outside the normal document flow, such as those positioned via position: absolute? Multiple consecutive whitespace characters that are rendered as a single visible character by the browser?

Having said all that, I have recently had a go at writing code to do this, and yes, it does involve DOM manipulation (although not that horrendous). It's extremely rudimentary and doesn't deal satisfactorily with any of the above issues, partly because I knocked it up quite quickly for a question on SO, and partly because in general I don't think it's possible to deal nicely in general with all those issues. The following answer provides functions for saving and restoring the selection as character indices within an editable element: replace innerHTML in contenteditable div

Community
  • 1
  • 1
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Hi Tim, thanks for taking the time to reply! The biggest problem I have with the DOM method is if I have a repeated sentence how do I know which one was highlighted? (i.e. CONTENT: Hello World! Hello World! ). Also what I mean by absolute is simply the number of characters from the start of the parent container to the positions of the selection boundaries (so a
    would be 4, the span opening above is 26 etc). If I have this information I can grab the contents complete with (partial) tags etc and choose how to handle the data.
    – Paul Norman Apr 11 '11 at 09:25
  • @Paul: You seem to be thinking of the DOM as the string of HTML from which the browser initially constructed the page. This isn't generally a helpful way to think of it. Firstly, the DOM is a tree. Secondly, once the the browser has constructed the DOM from the page's HTML, there is no reliable way of getting that initial HTML string back, so any offset within that string is essentially meaningless. What is it that you're actually trying to do? – Tim Down Apr 11 '11 at 09:35
  • I'm not confused by the DOM at all, but I'm also not interested in it! I just want to be able to return the HTML content of the highlighted area (including any tags it contains) to the JS function and know the start / end positions of it within the HTML. I really can't believe that more people don't! No hidden agenda, no required use case, I'd genuinely just like to know how to do it reliably. – Paul Norman Apr 11 '11 at 09:48
  • @Paul: OK. Sorry if I sounded condescending. However, I still don't see why offsets within a string representation of the DOM are useful, which is why I wanted to know what you wanted to do with that information once you'd got it. – Tim Down Apr 11 '11 at 10:05
  • Hi Tim, I'm not offended, just trying to clarify that I just want the position of the text selection within the div. With that you could operate on the contents simply via AJAX calls, wrap the selection in new tags while correcting for partial tags etc, but again I have no plans for it, just rather have a string to work with. I've updated the code to a version that kind of does what I was looking for, but there must be a proper and less sloppy way to do this! – Paul Norman Apr 11 '11 at 10:26