25 November 2009

Javascript: Get/Set Caret Cursor position in iframe WYSIWYG editor

I've been working on this for 3 months now on and off, using code snippets from the net and asking questions in forums, etc. I'm trying to get a RTE to autosave as the user is typing. I still don't have a viable solution that works cross browser but I will keep this post updated as I progress. The following works in Firefox:

The idea is that we insert an image as a marker (I use a nice loading symbol in an animated gif). Later or immediately afterwards, we can select the image and remove it, restoring the caret to it's original position. Here's the code:

Please see right hand panel before copying >

//before the save:
insertAtCursor("myIframe",'<img src="images/marker-autosave.gif" id="caret" />', 0); //change 0 to 1 if you want the user's selection to be replaced by the img

//after the save:

function insertAtCursor(iframename, text, replaceContents) {
      if(!replaceContents){//collapse selection:
         var sel=document.getElementById(iframename).contentWindow.getSelection()
      document.getElementById(iframename).contentWindow.document.execCommand('insertHTML', false, text);

function resetCaret(iframename){
      var iframe=document.getElementById(iframename).contentWindow
      var referenceNode = iframe.document.getElementById("caret");
         var sel=document.getElementById(iframename).contentWindow.getSelection()
  var range=sel.getRangeAt(0);
  var range=iframe.document.createRange()


Anonymous said...

great helped me a lot!
thank you very much!

Anonymous said...

'insertHTML' !!!
it's the greatest solution :)
"Shortness - the sister of talent"
thanks :)))

pawanch said...

This works great but doesn't work fine when you need to create a text bold.Then it gives some problem and wont allow you to create hyperlinks as well. Can you suggest something better like this.

Anonymous said...


Priyeranjan Singh said...

how can i maintain the cursor position in froala editors after enter key press

Post a Comment

Cron Design Studio: Dublin based web design & software development