Search code examples
javascriptjqueryfocuscontenteditableonkeyup

JS/jQuery : Amend contents of div contenteditable and refocus


My Aim:

To be able to add/amend the content inside my content editable user input div on 'keyup' and be able to refocus it so that the user is not interupted.

My Problem:

Content Editable div fails to properly refocus.

My Example:

http://jsbin.com/owoto4/4/


Solution

  • I have come up with a solution that is more effective than the .focus() method:

      $.fn.placeCaretAtEnd = function(){
        var el = $(this)[0];
        el.focus();
        if (typeof window.getSelection != "undefined"
          && typeof document.createRange != "undefined") {
          var range = document.createRange();
          range.selectNodeContents(el);
          range.collapse(false);
          var sel = window.getSelection();
          sel.removeAllRanges();
          sel.addRange(range);
        } else if (typeof document.body.createTextRange != "undefined") {
          var textRange = document.body.createTextRange();
          textRange.moveToElementText(el);
          textRange.collapse(false);
          textRange.select();
        }
      }
    

    USAGE:

    $('#myContenteditable').placeCaretAtEnd();