views:

313

answers:

2

I'm trying to allow the user to edit a contenteditable div, but am finding that I can't use pasteHTML unless there is some text selected.

I thought document.selection.createRange() would return a valid zero-length selection (i.e. a position), but alas no.

I've really struggled to find any solution to this that doesn't involve iframes (not an option at present).

Any suggestions/ideas/questions most welcome.

A: 

You could use a form textarea. This is simple and cross-browser, but don't know to what extent your styling is limited or whether using a form or form element is appropriate for your issue.

Richard
Unfortunately, this isn't an option for me, but thanks.
jezmck
+1  A: 

Make sure the focus is on the editable div before creating the TextRange from the selection:

var div = document.getElementById("your_div");
div.focus();
document.selection.createRange().pasteHTML("<b>PASTED</b>");
Tim Down
Thanks, already doing that anyway! Seen this mentioned a few times, but never an explanation as to why it matters.
jezmck
The above code works for me. If it isn't working for you then you're going to need to post the code you're using. As to why it matters: if the selection is empty and the focus is not on the editable element, IE seems to not consider it the selection for the document. Moving the focus to the element solves this.
Tim Down
I think this may actually be the cause afterall. I suspect that NicEdit, for which I'm trying to make a table plugin, is moving the focus at some point.
jezmck