Add Text in Textarea Using Button & Change Cursor Position

We as designers or developers strive to make our users' experience more intuitive. Sometimes clicking a button to carry out a job is a lot more fun than typing a command to do the same. Below is a simple example of doing such a thing. We are adding a code tag in our textarea using a button to make it easy for our users to type or paste the code in our community project.

Step 1: Add tag in the textarea by clicking the button


<textarea id="textareaId"></textarea>
<button onclick="addCode()">Add code</button>


let inputEl = document.getElementById('textareaId');
	inputEl.value = inputEl.value + "<code></code>";

Step 2: Put the tags at current cursor position

let pos = inputEl.selectionStart;
let val = inputEl.value;
let start = val.substring(0, pos);
let end = val.substring(pos, val.length);
inputEl.value = start + "<code> </code>" + end;

Step 3: Bring the cursor between and

inputEl.selectionStart = pos - 7;
inputEl.selectionEnd = pos - 7;

Tada! We not just added the code tag inside the textarea but also moved our cursor between and tags. I hope this will also save time and effort of our users.