On a HTML input field that has some padding defined, clicking on the padding area sets the cursor at the beginning of the line and not at the end.
Why is that happening? What would be a use case for this behaviour?
Any idea on how to prevent this and move always the cursor at the end of the line?
<input style="padding:25px;font-size:25px" value="hello" />
https://jsfiddle.net/sf4x3uzL/1
Check the snippet, the code is bit long but manages to work in all scenarios.
Here added a function to check if the click is from padding area from here
Added another function to get the caret position, and combined both function to get get the desired result.
var carPos = 0;
(function($) {
var isPaddingClick = function(element, e) {
var style = window.getComputedStyle(element, null);
var pTop = parseInt( style.getPropertyValue('padding-top') );
var pRight = parseFloat( style.getPropertyValue('padding-right') );
var pLeft = parseFloat( style.getPropertyValue('padding-left') );
var pBottom = parseFloat( style.getPropertyValue('padding-bottom') );
var width = element.offsetWidth;
var height = element.offsetHeight;
var x = parseFloat( e.offsetX );
var y = parseFloat( e.offsetY );
return !(( x > pLeft && x < width - pRight) &&
( y > pTop && y < height - pBottom))
}
$.fn.paddingClick = function(fn) {
this.on('click', function(e) {
if (isPaddingClick(this, e)) {
e.target.setSelectionRange(carPos, carPos);
fn()
}
})
return this
}
}(jQuery));
$('input').paddingClick()
$('input').bind('click keyup', function(event){
carPos = event.target.selectionStart;
})
.as-console{ display:none!important}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input style="padding:25px;font-size:25px" value='hello' />
You can use setSelectionRange
to set the position of the cursor to the end of the input element on click.
input.addEventListener('click', (e) => {
// Do not do anything if the user already has a selection range,
// for instance from a double click.
const { selectionStart, selectionEnd } = input;
if (selectionStart !== selectionEnd) return;
const { length } = input.value;
input.focus();
input.setSelectionRange(length, length);
});
<input id="input" style="padding:25px;font-size:25px" value="hello" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With