0

I would like to move the selected text from one content div to another content div. And the selected text should append at the current caret position of the other div. Is there any way to get care position based on div id ? I observed in all the sources,the obtained caret position is always based on selection .

<body >
 <div contenteditable="false" id='selectfromhere' >
   some text select
  </div>
   <div contenteditable="true" id='movehere' >
   some
  </div>
  <button>Click me</button>
</body>
isherwood
  • 58,414
  • 16
  • 114
  • 157
seetha
  • 199
  • 2
  • 7

2 Answers2

2

Try this:

var selectedText = '';

$(document).ready(function() {
  $('#selectfromhere').mouseup(function() {
    selectedText = window.getSelection().toString();
    console.log(selectedText);
  });

  $('button').click(function() {
    $('#selectfromhere').html($('#selectfromhere').html().split(selectedText).join(""));
    $('#movehere').append(selectedText);
  window.getSelection().removeAllRanges();
    selectedText = '';
    console.log('Some Text ' + selectedText);
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div contenteditable="false" id='selectfromhere'>
    some text select
  </div>
  <div contenteditable="true" id='movehere'>
    
  </div>
  <button type="button">Click me</button>
</body>

Hope it answered you question /Zorken17

Zorken17
  • 1,896
  • 1
  • 10
  • 16
  • I have edited the code so now you can choose multiple times to copy text from the first element. If this answered you question please mark it as one. – Zorken17 Dec 09 '15 at 14:51
0

Here is a solution for getting the caret position of a content-editable : Get caret position in contentEditable div

If you use that function to get an integer value for caret position (var caretPosition), the following should insert your text:

var insertText = $("#selectfromhere").html();
var currentText = $("#movehere").html();
var output = [currentText.slice(0, caretPosition), insertText, currentText.slice(caretPosition)].join('');

$("#movehere").html() = output;
Community
  • 1
  • 1
Branden Keck
  • 462
  • 3
  • 12
  • Get caret position in contentEditable div link is returning caret position of selectfromhere div. Could you please let me know, how to get the caret position of movehere div, so that i can move the text to that caret position from selectfromhere div – seetha Dec 09 '15 at 14:07
  • Within this function.... "var update = function() { $('#caretposition').html(getCaretPosition(this)); }; $('#contentbox').on("mousedown mouseup keydown keyup", update); " Did you make sure to replace #contentbox with #movehere and not #selectfromhere – Branden Keck Dec 09 '15 at 14:26