1

Here is the jsFiddle of what I am trying to achieve.

Example

HTML:

<div id="replaceme" contenteditable>Hello I am to be replaced. But the cursor position inside this div needs to be retained after replacement.</div>
<button>REPLACE</button>

JavaScript:

btn = document.querySelector('button')
btn.onclick = function() {
var replace = document.querySelector("#replaceme");
    replace.outerHTML = '<p id="replaced" contenteditable>' + replace.innerHTML + '</p>';
}

Basically, there is a div with some content and it's editable. The element need not be just div. It could be anything like p or h1 etc.

I am going to do the following:

  1. Place the cursor inside the div. Let's say I place my cursor after the text 'Hello I am to be replaced.'

  2. Click the button 'REPLACE'. This basically replaces the div with p but innerHTML of the new p is same as the old div.

  3. Now the cursor position is lost as I am having a new set of DOM elements, even though the contents of the dom are same.

Basically, I want to replace the tag without losing the caret position and I am not using jQuery for this project.

Cerbrus
  • 70,800
  • 18
  • 132
  • 147
shankardevy
  • 4,290
  • 5
  • 32
  • 49
  • How can you keep cursor position if you press the button. If you press the button cursor is gone... – coder hacker May 05 '14 at 07:04
  • @TejasPatel: Save the cursor location when the field is clicked, and on keypress. – Cerbrus May 05 '14 at 07:08
  • maybe I am wrong, but if you look at this jsfiddle (http://jsfiddle.net/TwGj8/1/), where I change the code for button to execute 'bold' command. I place the cursor inside the text and click the button. the caret position seems like lost but it's not. You can just type and you will see the characters are entered right at the same position before you clicked the button. I am looking for similar thing in my question posted. – shankardevy May 05 '14 at 07:10
  • Check http://stackoverflow.com/questions/4811822/get-a-ranges-start-and-end-offsets-relative-to-its-parent-container/4812022#4812022 it might help to get carret position which you can save and use latter – coder hacker May 05 '14 at 07:14
  • Do you want to do this on Internet Explorer <9 or on other standard browsers too? It may change *a lot*. – MaxArt May 05 '14 at 07:42

0 Answers0