0

When I bring up jQuery dialog prompt for inserting a picture, I lose the caret position in my designmode on iFrame. How would I go about inserting the picture at the previous caret position without having to re-place the caret by hand before submitting? I am pretty sure it has to do with getting the range, because on default it selects the start of the frame.

Here is my code- It works fine only you have to select the position to place the image once again after pasting the URL in the prompt.

var iframe = document.getElementById('editor');   
var iframeDocument = document.getElementById('editor').contentDocument || document.getElementById('editor').contentWindow.document;
iframe.contentWindow.focus()
var sel, range;
if (iframe.contentWindow.getSelection) {
    sel = iframe.contentWindow.getSelection();
    if (sel.getRangeAt && sel.rangeCount) {
        range = sel.getRangeAt(0);
        range.deleteContents();
        var el = document.createElement("div");
var el = iframe.contentDocument.createElement("div");
el.innerHTML = html;
var frag = iframe.contentDocument.createDocumentFragment(), node, lastNode;
        while (node = el.firstChild) {
            lastNode = frag.appendChild(node);
        }
        range.insertNode(frag);
Clint
  • 169
  • 1
  • 12
  • Have you seen this one? http://stackoverflow.com/questions/6690752/insert-html-at-caret-in-a-contenteditable-div – Roko C. Buljan Jan 24 '15 at 03:29
  • Yup! I actually based my code off of that. The problem is that I am using a jQuery dialog rather than a prompt, which results in losing the selection. Because of this I need a reliable method of getting the selection and re-selecting it via javascript. – Clint Jan 24 '15 at 03:34
  • 1
    Use Goog and follow Tim's answers (suffix with `:stackoverflow` in Goog) He has done an amazing work over contenteditable and selections over the past years. There's nothing to add to. I'm certain the answer lies somewhere in his posts. – Roko C. Buljan Jan 24 '15 at 03:47
  • Also to warn you, if you think your question is way out of what you could find browsing or on this pages, please, post the minimal code to reproduce your issue. Using your JS-only, I cannot even think where you're lost at. [ask]. Happy coding and thumbs up! – Roko C. Buljan Jan 24 '15 at 03:51
  • 1
    Thanks for the tip, I'll try googling with that suffix! – Clint Jan 24 '15 at 03:57

0 Answers0