I used the jQuery binding function, which calls the "editableContentChanged" function whenever a div has one of the following events: "blur keyup paste copy cut mouseup". You can look at the documentation and add events to the binding function if you need to. The editableContentChanged function first replaces the contents of the div being edited, and then calls the setCaret method, which places the cursor at the end of the content. Heres a working example https://jsfiddle.net/vacfkono/4/
HTML
<tr> <td>One Off Capital</td> <td><div contenteditable>fadsfasd </div></td> <td><div contenteditable> fasdfasd </div></td> </tr>
Javascript / jquery
$(document).ready(function () { $('div').bind('blur keyup paste copy cut mouseup', editableContentChanged); }); var maxLength = 20; function editableContentChanged() { if($(this).html().length >= maxLength) { $(this).html($(this).html().substring(0, maxLength-1)); setCaret(this); } } function setCaret(el) { var range = document.createRange(); var sel = window.getSelection(); range.setStart(el.childNodes[0], 19); range.collapse(true); sel.removeAllRanges(); sel.addRange(range); el.focus(); }
source share