2

I have div tag with contentEditable = 'true'. When I enter text from my keyboard and then call the undo function (document.execCommand('undo',false, null)), all of the text I entered is deleted. I want to just undo the last character typed. How can I do that?

function doUNDO() 
{
    document.execCommand('undo',false, null);
}
<!DOCTYPE html>
<html>
    <head>
        <script src="formulas.js"></script>
        <link rel="stylesheet" href="styles.css" type="text/css" media="screen" />
    </head>
    <body id="main" spellcheck="false"> 
        <span contenteditable="false">
            <button onclick="doUNDO()">UNDO</button>
        </span> 

        <div id = "mainDiv"contenteditable="true">a</div>  
    </body>
</html>
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
Nikita Ermolenko
  • 2,139
  • 2
  • 19
  • 41
  • 1
    This is an uncommon pattern. Usually 'undo' refers to a segment of typing - and not 1 character. The delete key is already there when a keyboard is available. Usually 'back' is for removing the last character. – sheriffderek Aug 19 '15 at 15:49
  • A little more explanation might be in order. Is someone writing an essay in this div - or something long that they traverse and edit in many places? – sheriffderek Aug 19 '15 at 15:51
  • What if I delete a word, and then I want to undo that action? – sheriffderek Aug 19 '15 at 15:57
  • This seems to be what you're looking for. http://stackoverflow.com/questions/16225718/unable-to-get-document-execcommandundo-working-in-the-same-manner-across-bro – sheriffderek Aug 19 '15 at 16:03
  • @sheriffderek: No, that's about using commands on textareas rather than contenteditable divs, not about changing the action of the command. – T.J. Crowder Aug 19 '15 at 16:06
  • I don't think you can do this without a *substantial* amount of work that will probably require a great deal of cross-browser testing. I've tried a few things to try to make the browser mark an edit point so Undo does what you want, but not had any luck at all. I'm sure there's a way, but I bet (again) it's complicated and browser-sensitive. – T.J. Crowder Aug 19 '15 at 16:20
  • Thank you for answers! But i change div tag to input tag and this problem disappeared :) – Nikita Ermolenko Aug 19 '15 at 16:24

1 Answers1

-1

In doUndo() instead of calling execCommand you could just remove the last character from the div, if it is not empty.

E.g.

function doUNDO() {
    var mainDIV = document.getElementById('mainDiv') 
    mainDIV.innerHTML = mainDIV.innerHTML.substr(0, mainDIV.innerHTML.length - 1);

}

Mahout
  • 414
  • 1
  • 3
  • 12
  • The last character typed is not necessarily -- indeed, *frequently* not -- the last character in the div. Further, setting the div's `innerHTML` will probably screw up the position of the insertion point. – T.J. Crowder Aug 19 '15 at 15:48
  • This logic doesn't help me, because my div tag can contains another tag on last position. – Nikita Ermolenko Aug 19 '15 at 16:08