Key events (beforeinput, input, keyup, etc...)

Cursor is jumping to the end of the input when value of the input is changed

by Konstantin Rouda

HTML

<input type="text" id="inp" value="12345678">

JavaScript

;(function () {
	"use strict";
  
  const inp = document.getElementById("inp");
  
  let oldVal;
  let prevSelectionStartValue;   
  let prevSelectionEndValue;
  
  inp.addEventListener("keydown", function (e) {
    debugger;
    
    /// calling in this event e.preventDefault() will prevent key from being clicked
    //e.preventDefault(); 
    
    ///this.setRangeText("", 4, 4);
    
    ///this.setSelectionRange(this.selectionStart, this.selectionStart);
    
    /*e.stopImmediatePropagation();
    e.stopPropagation();*/
  });
  
 inp.addEventListener("beforeinput", function (e) {
    debugger;
   
    oldVal = e.currentTarget.value;
        
    prevSelectionStartValue = this.selectionStart;   
    prevSelectionEndValue = this.selectionEnd;
    
    /*e.preventDefault(); 
    
    e.stopImmediatePropagation();
    e.stopPropagation();*/
  });
  
  
  inp.addEventListener("input", function (e) {
    debugger;
   
   //// selectionStart/End position should be safed prior to the change of the input's value
   /// otherwise it will be changed to the end position of the input's text

   
   
    e.currentTarget.value = oldVal;
    
    /// NOTE: This Event Can not be canceled
    
    this.setSelectionRange(prevSelectionEndValue, prevSelectionEndValue);
    
    /*
    e.stopImmediatePropagation();
    e.stopPropagation();*/
  });
  
  inp.addEventListener("keyup", function (e) {
    debugger;
   
    //e.currentTarget.value = oldVal;
    
    
    /*e.preventDefault();*/ 
    
   /* e.stopImmediatePropagation();
    e.stopPropagation();*/
  });
  
})();