0

Here is the javascript code I am using and I want to highlighted the characters after 255 and should be shown in another div with diff color

$( "#testdiv" ).keyup(function() {
   if($("#testdiv").text().length>255)
   {
   var text = $("#info").text()
   $("#testdiv").text("")
   $("#testdiv").append(text.slice(0,255)+"<div>"+text.slice(255)+"</div>")
   }
});

Here is the HTML code,

<div id="testdiv"  contenteditable="true">
</div>

With this code the problem I am facing is

  1. It is updating the cursor position to the beginning of text when I try to update text after 255 characters.
  2. When there is less than 255 character inside div and I press enter then every time it appends a div enclosing the <br> tag.
3
  • try $("#testdiv").append(text.slice(0,255)+"<div>"+text.slice(255)+"</div>").focus();
    – daulat
    Mar 31, 2017 at 10:47
  • for first point
    – daulat
    Mar 31, 2017 at 10:48
  • @daulat: it didn't work Mar 31, 2017 at 10:51

1 Answer 1

0

$("#testdiv").on('keyup', function() {
  if ($("#testdiv").text().length > 255) {
    var text = $("#testdiv").text()
    $("#testdiv").text("");
    $("#testdiv").html(text.slice(0, 255) + "<div style='color:red'>" + text.slice(255) + "</div>");

    var preHtml = $("#testdiv").html();
    $("#testdiv").html(preHtml);

    $("#testdiv").focus();
    placeCaretAtEnd(document.getElementById("testdiv"));

  }
});

function placeCaretAtEnd(el) {
  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();
  }
}
<div id="testdiv" contenteditable="true">sample text
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>

2
  • Kapila Perera in you result as well the cursor is moving to the beginning Mar 31, 2017 at 11:18
  • 1
    Kapila Perera : in updated code cursor moves at end instead of beginning. I want it to stay where I am inserting text. Mar 31, 2017 at 11:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.