Rangy move boundaries of user selection out of header element

Posted by Frank on Stack Overflow See other posts from Stack Overflow or by Frank
Published on 2012-09-12T03:34:49Z Indexed on 2012/09/12 3:38 UTC
Read the original article Hit count: 107

Filed under:

I'm using rangy and have a case with a contenteditable div where the users selection can be saved and later restored so that HTML can be inserted.

My problem is that if the user selects within a header element, I don't want the html inserted within a header.

So I'm trying to figure out how to use rangy so that if the the selection is made within a header then I can move it before the header element.

So if the user selects within an h1:

<div id="editable" contenteditable>
     <h1>|user selects here| Header Text</h1>
</div>

Then the saved selection would be moved before the h1:

| selection boundary moved here |<div id="editable" contenteditable>
     <h1>|user selects here| Header Text</h1>
</div>

I've tried the following to see if I could move the selection boundary:

var sel = rangy.getSelection();
var range = sel.getRangeAt(0);

range.setStartBefore(sel.anchorNode.parentNode);

sel.removeAllRanges();
sel.addRange(range);

selected = rangy.saveSelection();

But when I select within the H1, it still sets the saved selection boundaries within the H1 and not before it. I'm not sure how I can get the boundaries moved before the header element.

© Stack Overflow or respective owner

Related posts about rangy