The text cursor moves to the left after each character
This is a bug related to the code I made.
I was making a text length check box, came up with some working code. However, what I am doing here is causing the Text cursor to move to the left every time you type, which means that the typed text comes out backwards or in a mess.
What's going on below, what could be causing this? I would guess a splicing probably?
JSFiddle and jQuery below
$(function(){
var charLimit = 10;
$('.input').keypress(function(e){
if (e.which > 0){
var string = $(this).text().split("");
for(i=0;i<charLimit;i++){
if(string[i] !== undefined){
string.splice((charLimit-1),0,"<span class='error'>");
string.push("</span>");
}
}
$(this).html(string.join(""));
}
});
});
+3
source to share
1 answer
Use this function to always place the cursor at the end:
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();
}
}
Use it after
$(this).html(string.join(""));
like this:
placeCaretAtEnd( document.getElementById(".input") );
You can search: http://jsfiddle.net/nh9hbxdf/
This can be achieved with some CSS tricks:
here's the updated code:
<p id="output"></p>
<textarea></textarea>
<style>
textarea, #output {
width: 500px;
height: 10em;
padding: 0.2em;
margin: 0.2em;
box-sizing: border-box;
font: 13px arial;
border: 1px solid silver;
white-space: pre-wrap;
}
textarea {
position: relative;
-webkit-text-fill-color: transparent;
overflow: auto;
}
#output {
position: absolute;
pointer-events: none;
z-index: 1;
}
#output span:first-of-type {
color: red;
/*background-color: blue;*/
}
.error{
color:red;
}
<script>
$(document).ready(function(){
$('textarea').on('input', function() {
$('#output').html(this.value.replace(/^(.{10})(.*)$/, '$1<span class="error" contenteditable>$2</span>'));
});
$('textarea').focus();
});
</script>
+3
source to share