With Rangy, even though I extend the range by setStartBefore method, range.canSurroundContents method still returns false

I have the following html:

<p>Morbi quis augue vitae quam <a href="#">pharetra| varius</a> at at| urna.</p>

The selection is marked with | characters. Also a screenshot of the selection:

Screenshot of the original selection

I can extend this selection to contain the whole 'a' element with the following code snippet (using Rangy library http://code.google.com/p/rangy/):

$('body').on('mouseup', '[contenteditable]', function() {
var block = this,
    sel = rangy.getSelection(),
    range = sel.getRangeAt(0);

if (sel.anchorNode.parentNode !== block) {
    range.setStartBefore(sel.anchorNode);
    sel.setSingleRange(range, false);
    sel.refresh();
}
});

To see it in action, check http://jsfiddle.net/LTwkZ/1/

And also the following returns true:

range.containsNode(anchorNode);

The problem is 'range.canSurroundContents()' returns 'false'. 'a' element is fully contained by range, from start to the end, why can not use 'canSurroundContents()' and how can I, if possible of course.

Thanks!

Answers:

Answer

I think the problem is that anchorNode is the text node within the link rather than the link itself, so the selection starts within the link rather than before it. Moving the start of the range before the link should fix it. Also, there is no need to call refresh() on the selection unless something other than Rangy has modified it, although that won't be causing any problems here.

Revised jsFiddle: http://jsfiddle.net/LTwkZ/2/

Code:

$('body').on('mouseup', '[contenteditable]', function() {
    var block = this,
    sel = rangy.getSelection(),
    range = sel.getRangeAt(0);

    if (sel.anchorNode.parentNode !== block) {
        range.setStartBefore(sel.anchorNode.parentNode);
        sel.setSingleRange(range, false);
    }
});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.