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/

2
  • var len = textBox.innerText.length + 2 will move the cursor to the end of the input. Commented Feb 5, 2019 at 12:51
  • This might help stackoverflow.com/a/10782169 Commented Feb 5, 2019 at 23:19

1 Answer 1

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; } 
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, but did you know a way to move the text to the and, that I could see the caret?
If you add new item you would like move cursor to the right and show scrollbar?
I wont the same behavior as when you just put some text, the text need to move left.
Try now, I hope that helps you :)
I'd change the overflow-x to auto instead of scroll.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.