Home > Back-end >  Recreate Delete key functionality
Recreate Delete key functionality

Time:11-09

As I can tell it's not possible to just assign delete keycode to another key, so I tried to recreate its functionality, but I can't figure out how to do it properly.

I tried to do it with slice, and it actually does what it should for the first time, but then any key I press triggers delete.

    window.addEventListener("keydown", function(e) {
        let formuleInput = $(".mat-input-element");
        if ($(formuleInput).is(':focus')) {
            formuleInput[0].addEventListener('keyup', function(f) {
                let caretPos = f.target.selectionStart;
                console.log(caretPos);
                let fInput = formuleInput[0].value;
                if (e.keyCode === 32 && $(formuleInput).is(':focus')) {
                    e.preventDefault();
                    fInput = fInput.slice(0, caretPos)   fInput.slice(caretPos   1);
                    formuleInput[0].value = fInput;
                }
            })
        }})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" >

CodePudding user response:

This should work, but you don't need jQuery to do it. Attach the event to the input instead of the window. That way you don't have to capture every single keypress event and filter it based on the input.

This uses the keydown event to remove the default functionality of adding a space on the key 32's default behavior and then uses the substring argument to remove the last typed character from the input value.

(function(){
    let formuleInput = document.querySelector(".mat-input-element");
    formuleInput.addEventListener("keydown", function(e){
        if (e.keyCode === 32) {
            e.preventDefault();
        }
    });
    formuleInput.addEventListener("keyup", function(e){
        let fInput = formuleInput.value;
        if (e.keyCode === 32) {
            e.preventDefault();
            formuleInput.value = fInput.substring(0, fInput.length - 1);
        }
    });
})();

CodePudding user response:

To make the spacebar act the same as the delete key does, for both selected and unselected text:

const myInput = document.getElementById('my-input');

myInput.addEventListener("keydown", (e) => {
  emulateDeleteUsingSpace(e);
}, false);

function emulateDeleteUsingSpace(e)
{  
  let caretStartPos = e.target.selectionStart;
  let caretEndPos = e.target.selectionEnd;
  
  // when nothing is selected we delete a single character to the right of the caret
  if (caretEndPos === caretStartPos && caretEndPos < e.target.value.length) 
    caretEndPos  = 1;
  
  if (e.keyCode === 32)
  {
    e.preventDefault();        
    e.target.value = e.target.value.substring(0, caretStartPos)   e.target.value.substring(caretEndPos); // delete    
    e.target.selectionStart = e.target.selectionEnd = caretStartPos; // reposition caret
  }
}
<input type="text" id="my-input">

  • Related