How would you remove the ability to change cursor position in an input field. So when a user types, they will always type at the end.
3 Answers
You might hit some old browser limitations with this one, but just to get you an idea.
You'll need to handle both paste and keydown events. For the paste you might need the Clipboard API to the rescue. Enough talking, here it goes:
function setRng(el, txt, from, to) {
el.setSelectionRange(from + txt.length, to + txt.length);
}
function insVal(el, txt, from, to) {
from = Math.max(0, from);
to = to || from;
el.value = el.value.substring(0, from) + txt + el.value.substring(to, el.value.length);
setRng(el, txt, from, from);
}
function writeToEnd(ev) {
var el = ev.target;
var key = ev.keyCode;
var isBackspace = key === 8;
var isPaste = ev.type === "paste";
var txt = isPaste ? (ev.clipboardData || window.clipboardData).getData('Text') : '';
var fromOffset = isBackspace ? -1 : 0;
if (txt && txt.length > 1 || isPaste || isBackspace) ev.preventDefault(); // Cause of some special input
insVal(el, txt, el.value.length + fromOffset, el.value.length);
}
[...document.querySelectorAll('.writeToEnd')].forEach(el => {
el.addEventListener('keydown', writeToEnd);
el.addEventListener('paste', writeToEnd);
});
<input class="writeToEnd" type="text" value="input test"><br>
<textarea class="writeToEnd">textarea test</textarea><br>
(Test also COPY/PASTE using mouse and keyboard)
3 Comments
Tim
Thanks! It works great. I didn't think of the copy/paste. There is only a small bug. It doesn't work with backspace. Otherwise this has been the best answer thanks!
Tim
Sorry for bugging you again. When you hit backspace, it removes two characters instead of one.
Roko C. Buljan
@Tim sorry when refactoring the code I forgot to add
|| isBackspaceThis code will not stop user from changing the position of cursor but it won't allow user to write in between the text.
Please try this
function writeAtLast() {
var textbox = document.getElementById('text');
textbox.setSelectionRange(textbox.value.length, textbox.value.length);
};
<input id="text" type="text" class="txtbox" onkeypress='writeAtLast()' onCopy="return false" onDrag="return false" onDrop="return false" onPaste="writeAtLast()" autocomplete=off />
7 Comments
Roko C. Buljan
You forgot that one can use
copy / paste? Also, please, teach people to use Element.addEventListener(). Also, querying the DOM on every single keystroke is such a bad idea.Ashu
Thank you for the information, we can try blocking paste on the text box. Let me edit it. Will check on addEventListerner too
Roko C. Buljan
Block? Why? I'd instead simply try to improve the necessary code to achieve the desired without destroying user experience.
Ashu
Changed it to handle the paste scenario to paste also at last of the text.
Roko C. Buljan
You just destroyed classic copy/paste functionality :\
|