Skip to content
Advertisement

Clicking on the padding of an input field sets the cursor at the beginning of the line, not at the end

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?

enter image description here

<input style="padding:25px;font-size:25px" value="hello" />

https://jsfiddle.net/sf4x3uzL/1

Advertisement

Answer

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' />
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement