We have a requirement, where we need to insert some HTML into a telerik RAD editor control, at the current cursor position.
I thought this was going to be a peice of cake. Firstly, I didn’t realise that the telerik RAD editor control actually used an iframe, with an internal DOM set to designMode = “on”. This basically instantiates a document in “edit” mode, and within internet explorer (and I believe this works for most other browsers) will let you edit and paste HTML content – a likely choice for most hardcore text-editors for the web.
After finding this information out – I stumbled upon an awesome read, how this guy had created a javascript syntax highlighter, through the means of a DOM in designmode, and javascript itself. He ended up writing an entire parser, lexer, and tokenizer within javascript to interpret the entire script to make the highlighter work nicer, and he also managed to make it aware of scoped variables…cool.
http://marijn.haverbeke.nl/codemirror/story.html
Anyhow, I started studying the various ways he went about implementing the selection system.
I ended up, after all of my study, working out how it can be done – and yes, as usual, it’s one line of code, and a very simple operation. I have only tested this in IE so far:
document.getElementById(‘myEditorIframe’).document.selection.createRange().pasteHTML(“<a href=’http://www.google.com.au’>My pdf name</a>”);
Brilliant! Now all I need to do is create a tiny bit of client side script to do the above, and I’ll be laughing!
Hope this helps someone else out!
M
EDIT:
Alright, so this doesn’t work for firefox, I get it
It also doesn’t work for IE7, by the looks of it. In any case, I scoured the net and found this function which seems to work in firefox + IE6, haven’t tested it in IE7 (but I doubt it will work).
rteName = “Name of your editor IFRAME”;
function rteInsertHTML(html) {
if (document.all) {
var oRng = document.getElementById(rteName).contentWindow.document.selection.createRange( );
oRng.pasteHTML(html);
oRng.collapse(false);
oRng.select();
} else {
document.getElementById(rteName).contentWindow.document.execCommand(‘insertHTM L’, false, html);
}
};
Hi –
Did you figure out the firefox version? I had trouble googling even a reference – here are the issues:
1) selectionStart & selectionEnd disappeared in iframe
2) empty selection cannot be used to create range
3) empty selection also cannot add range
Thanks,
It’s really really help me a lot!!!
Thank you very much!
xxxxxx
Gracias por el codigo!!! justo lo que necesitaba!!
Great work!
In a , you can’t use “selection” so that the same method doesn’t work. Do you know a way to do the same thing in editable ?
Great work!
In <div>, you can’t use “selection” so that the same method doesn’t work. Do you know a way to do the same thing in editable <div>? Thanks.
It really helped me a lot.
thanks
this is not working in IE8.
Thank you, it helped me too
but doesn’t work on firefox, don’t you know how to do it?