1

I made the script to adjust div padding to user's input text accordingly. However, the code makes the cursor focus on the start of the contenteditable div after every keypress, I can't figure out why this is happening and wondering how to make the cursor behave normally.


HTML and CSS

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

<html>
box
<div class="comment_box" contenteditable="true"></div>

</html>
    <style>
    *{
    box-sizing: Border-box;
    font-family: "Lucida Grande", sans-serif;
    font-size:18px;
    border-radius:3px;


}
.comment_box{
  overflow:hidden;
    width:521px;
  padding:30px;
  text-align: left;
  height:80px;
  margin-top:5px;
  background-color:#ffcc99;
  word-wrap: break-word;

}
</style>

Javascript

<script>

$(".comment_box").keypress(function (e) {
    if (e.which !== 0 &&
        !e.ctrlKey && !e.metaKey && !e.altKey
    ) {
        var html_org = $(this).html();
    var html_calc = '<span>' + html_org + '</span>';
    $(this).html(html_calc);
    var width = $(this).find('span:first').height();
    $(this).html(html_org);
    if(width>21){
      $(this).css({"padding-top":"21px"});
    }
    }
});  

</script>

I have tried adding to the end of my script but it doesn't have luck.

$(".comment_box").focus();
stark
  • 2,246
  • 2
  • 23
  • 35
ryanpika
  • 151
  • 3
  • 13
  • 3
    Your code completely overwrites the contents of the element (twice!) on each keypress, so how would the browser magically know where the cursor was in the original content? (Note that the cursor may not have been at the end, if the user was trying to edit the middle.) – nnnnnn Feb 05 '16 at 00:14
  • Thanks.I see.. any idea achieve my goal? seems impossible though.. – ryanpika Feb 05 '16 at 00:51
  • There are techniques to get and set the cursor (caret) position. So get the position before you modify the text then later set it back to that position. Google "cursor position in contenteditable" and you'll find some information like [this SO answer](http://stackoverflow.com/a/24353415). Or an alternative approach might be to *not* change the div contents: copy the contents to another, off-screen div and do height/width calculations based on the other div. – nnnnnn Feb 05 '16 at 03:38
  • Thanks, I fixed my problem by creating another div for testing the width to signal the behavior of my target div – ryanpika Feb 05 '16 at 17:52

0 Answers0