Search code examples
javascriptjquerywebrangerich-text-editor

How to fix cursor position when prevent browser's default paste action


There is a custom method to insert HTML(html fragment not just plain text) into an editor (Rich Text Editor), but for some reason I have to use e.preventDefault to prevent browser default paste action and insert the copy data later. My code looks like below:

editor.addEventListener('paste', function(e) {
   var data = e.clipboardData.getData('text/html'),
       newData;
   e.preventDefault();
   newData = custom.handle(data);
   custom.insert(newData);
}, false); 

After custom.insert(newData), cursor is still blinking at the origin position. I expected it to have moved the end of newData.

Can anybody help me fix that?


Solution

  • I don't know what properties of functions your custom has, but you can use this the code to move the cursor to the end of the text in an input and textarea:

    custom.selectionStart = custom.selectionEnd;
    

    If newData is pasted in the middle or beginning of the text, then you will have to calculate the length of newData and move the cursor by that many characters. Something like:

    custom.selectionStart = custom.selectionStart + newData.length;
    custom.selectionEnd = custom.selectionStart;
    

    Edit to answer your question: How to calculate the length of text with HTML tags?

    Well, this will be a bit tricky. You can create a temporary HTML element in memory, add the newData in it, and calculate the length of its innerText property. Something like this:

    var temp = document.createElement("div");
    temp.innerHTML = newData;
    custom.selectionStart = custom.selectionStart + temp.innerText.length;
    custom.selectionEnd = custom.selectionStart;
    

    Note: innerText is was introduced by Microsoft and is not a W3C standard. The implementation varies across browsers although most replicate IE's behavior. innerText is style-aware and will only return the visible text.