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();