4

In my example i have 2 problems.

1.In the first click, the cursor not moved to the end.

2.In overflow, i need to alight text to the end, because there is free content input.

$("a").click(function(evt) {
  evt.preventDefault();
  var textBox = document.querySelector(".c_textBox")
  textBox.innerText += " hello  a,";
  var len = textBox.innerText.length + 1

  var range = document.createRange();
  var sel = window.getSelection();
  range.setStart(textBox.childNodes[0], len);
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
  textBox.focus();
});
.c_textBox {
  display: block;
  width: 200px;
  height: 40px;
  white-space: nowrap;
  overflow: hidden;
  font-size: 1.6rem;
  border: none;
  padding-right: 3rem;
  padding-left: 2rem;
  background-repeat: no-repeat;
  background-size: 2rem;
  /* background-position: 100% 50%;*/
  background-color: lightgrey;
  border: 2px black solid;
  padding: 4px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#">add item</a><br/>
<div contenteditable="true" type='text' id="searchInput" class="c_textBox"> </div>

http://jsfiddle.net/x3pf4nu2/

yantrab
  • 2,482
  • 4
  • 31
  • 52

1 Answers1

2

Try to use \u00a0 as an white space. Just like this:

$("a").click(function(evt){
  evt.preventDefault();
  var textBox = document.querySelector(".c_textBox")
  textBox.innerText +="\u00a0hello\u00a0\u00a0a,";
  var len = textBox.innerText.length
  textBox.scrollLeft += textBox.innerText.length;
  var range = document.createRange();
  var sel = window.getSelection();
  range.setStart(textBox.childNodes[0], len );
  range.collapse(true);
  sel.removeAllRanges();
  sel.addRange(range);
  textBox.focus();
});

And CSS:

.c_textBox{
  display:block;
  width:200px;
  height:40px;
  overflow-x: scroll;
  overflow-y: hidden;
  white-space: nowrap;
  background-color:lightgrey;
  border: 2px black solid;
  padding:5px;
}
Mat.Now
  • 1,715
  • 3
  • 16
  • 31