Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: How do I expand a user selection based on html tags?

Le Code: http://jsfiddle.net/frf7w/12/

So right now, the current method will take the selected text exactly as... selected, and add tags so that when it is displayed, the page doesn't blow up.

But what I want to do: Is to, when a user selects a portion of a page, if there are un-matched tags within the selection, the selection will either jump forward or backward (depending on what unmatched tag is in the selection) to the tag(s) that make the selection valid html.

The reason why I want to do this, is because I want a user to be able te select text on a page, and be able to edit that text in a WYSIWYG editor (I can currently do this with the linked code), and then put what they've edited back into the page (currently can't do this, because the method I use adds tags).

like image 234
NullVoxPopuli Avatar asked Oct 07 '11 16:10

NullVoxPopuli


1 Answers

The coverAll method in this SO answer has exactly what you want Use javascript to extend a DOM Range to cover partially selected nodes. For some reason extending Selection prototype does not work for me on my chrome, so I extracted the code and substituted this with window.getSelection(). Final code looks like this:

function coverAll() {
    var ranges = [];
    for(var i=0; i<window.getSelection().rangeCount; i++) {
        var range = window.getSelection().getRangeAt(i);
        while(range.startContainer.nodeType == 3
              || range.startContainer.childNodes.length == 1)
            range.setStartBefore(range.startContainer);
        while(range.endContainer.nodeType == 3
              || range.endContainer.childNodes.length == 1)
            range.setEndAfter(range.endContainer);
        ranges.push(range);
    }
    window.getSelection().removeAllRanges();
    for(var i=0; i<ranges.length; i++) {
        window.getSelection().addRange(ranges[i]);
    }
    return;
}
like image 193
Narendra Yadala Avatar answered Oct 12 '22 08:10

Narendra Yadala