<!--Problem: Cursor inside input should always be present at the end -- >
<!-- Problem: Cursor inside input should always be present at the end -->
<input type="text" value="hello world foo bar bak baz more text"><br><br>
<textarea>
hello world
foo bar
bak baz
more text
.
</textarea>
body {
body {
padding: 50px;
background: whiteSmoke;
}
input, textarea {
border: 1px solid lightGray;
padding: 10px;
}
textarea {
height: 200px;
width: 300px;
}
x
var input = document.querySelector('input');
var textarea = document.querySelector('textarea');
var old_val = '';
var reset = function (e) {
var val = this.value
, len = val.length;
this.setSelectionRange(len, len);
// To fix android chrome bug
// although good practise just incase
// user is using some other browser/os combination
// with similar issue.
if (e.type === 'keyup' || e.type === 'keydown') {
var short, long;
if (old_val.length < val.length) {
short = old_val;
long = val;
}
else {
short = val;
long = old_val;
}
if (long.indexOf(short) !== 0) {
val = old_val;
this.value = val;
this.setSelectionRange(old_val.length, old_val.length);
e.preventDefault();
// Just exit from the function now
return false;
}
}
old_val = val;
};
input.addEventListener('focus', reset, false);
input.addEventListener('mouseup', reset, false);
input.addEventListener('keyup', reset, false);
input.addEventListener('keydown', reset, false);
textarea.addEventListener('focus', reset, false);
textarea.addEventListener('mouseup', reset, false);
textarea.addEventListener('keyup', reset, false);
textarea.addEventListener('keydown', reset, false);