Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 698
Manuel Bitto Avatar asked Nov 06 '19 14:11

Manuel Bitto


2 Answers

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' />
like image 122
Akhil Aravind Avatar answered Nov 09 '22 07:11

Akhil Aravind


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" />
like image 26
Wex Avatar answered Nov 09 '22 07:11

Wex