Reputation: 175
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.
Upvotes: 4
Views: 1678
Reputation: 206565
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)
MDN Clipboard API,
Stack Overflow get-clipboard-data
Upvotes: 3
Reputation: 2266
This 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 />
Upvotes: 1
Reputation: 334
function changeCursorPosition() {
var ele = document.getElementById('txt');
//set cursor position here
ele.setSelectionRange(1, 1);
};
<input type="text" id="txt" onkeypress="changeCursorPosition()" />
Upvotes: -1