Q:

Basic JS: Adding characters at cursor position, while maintaining cursor position

Say I am making a basic Calculator that allows whole expressions to typed by the user. I'll use a simple <input> tag.
The user can type whatever they want, but I want to make it even easier for the client, I want to add a closing parenthesis immediately after they type (, so I set up my javascript to detect when ( is input by into the input field, then += a ) to the input field.
The problem with my code is that it adds the parenthesis to the end of the input, regardless of where they type the parenthesis, even at the beginning.
How can I add a character where ever the cursor is?
My code is as follows:

input = document.querySelector("input[type=text]");

input.addEventListener(`keyup`, (event)=>
{
  if(event.key === `(`)
  {
    input.value+=`)`;
  }
});
<input type="text" placeholder="Put mathematical expression"></input>

A:

I believe that should solve your problem.
let input = document.querySelector("input[type=text]");

input.addEventListener(`keyup`, (event) => {
    if(event.key === '(') {
        let cursorPos = input.selectionStart;
        input.value = input.value.substr(0, cursorPos) + ')' + 
                      input.value.substr(cursorPos);
    }   
});

