Note that there are some explanatory texts on larger screens.

plurals
  1. PORetain Caret (cursor) Position in a ContentEditable "div" after updating the child elements through javascript
    primarykey
    data
    text
    <p>I'm having difficulties in retaining the caret position in a content editable div after I update it through javascript.</p> <p>I have a div with a contenteditable attribute.</p> <pre><code>&lt;div id="form", contenteditable="true"&gt; &lt;/div&gt; </code></pre> <p>Let's say the user typed <strong>"Bacon is so good! I want more"</strong> I update the html inside the div where I wrapped certain words with a span. From the html above, it would turn into this:</p> <pre><code>&lt;div id="form", contenteditable="true"&gt; Bacon is so &lt;span&gt;good&lt;/span&gt;! I want more! &lt;/div&gt; </code></pre> <p>I do this by updating the html using jQuery...</p> <pre><code>$('#form').html(...here I put the updated html...) </code></pre> <p>However after this, the caret (cursor) returns to the start of the div. I want to keep the caret in the same position as before I update the div in order for the user to continue typing without any hitch.</p> <p>Currently, I have the following code:</p> <p>I first save the caret position prior to updating the div.</p> <pre><code>if(window.getSelection) { window.savedRange = window.getSelection().getRangeAt(0); } else if(document.selection) { window.savedRange = document.selection.createRange(); } </code></pre> <p>And then I try to return the caret position by</p> <pre><code>$('#form').get(0).focus(); if (window.savedRange != null) { if (window.getSelection) { var s = window.getSelection(); if (s.rangeCount &gt; 0) s.removeAllRanges(); s.addRange(window.savedRange); } else if (document.createRange) { window.getSelection().addRange(window.savedRange); } else if (document.selection) { window.savedRange.select(); } } </code></pre> <p>I need to retain the caret because this should all happen while the user is typing. The code above didn't do anything. It still returns to the start of the div. </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload