<textarea> のキャレットがある位置に、JavaScriptで文字列を挿入する方法を紹介します。
サンプルコード
<textarea> の現在のキャレット位置は selectionStart および selectionEnd で取得できます。ここで取得した位置を基準に文字を挿入します。
以下は、キャレットがある位置に “hello world” を挿入する例です。
const textarea = document.querySelector('textarea');
const strToInsert = 'hello world';
const startPos = textarea.selectionStart;
const endPos = textarea.selectionEnd;
const value = textarea.value;
textarea.value = value.substring(0, startPos) + strToInsert + value.substring(endPos, value.length);
textarea.selectionStart = startPos + strToInsert.length;
textarea.selectionEnd = startPos + strToInsert.length;
undo、redoは効かない
<textarea> のキャレット位置に文字列を挿入する方法は、JavaScriptで selectionStart とselectionEnd を使用して、キャレット位置を取得し、その位置に文字列を挿入することで実現できます。ただし、この方法では、挿入された文字列が元に戻されることはありません。つまり、undo、redo機能は効きません。
ボタンのクリックで文字を挿入
よくあるユースケースとして考えられるのが、ボタンをクリックすると特定のキーワードを <textarea> のキャレット位置に挿入するといった使い方であろう。例えばマークダウンエディタであれば、見出しを表す「##」などのキーワードを、ボタンクリックで挿入するといった感じだ。
以下は、ボタンクリック時に呼ばれ、<textarea> に文字を挿入する handleClick 関数の実装例である。
document.getElementById("btn")?.addEventListener("mousedown", handleClick)
function handleClick(e) {
const textarea = document.querySelector('textarea');
const strToInsert = 'hello world';
const startPos = textarea.selectionStart;
const endPos = textarea.selectionEnd;
const value = textarea.value;
textarea.value = value.substring(0, startPos) + strToInsert + value.substring(endPos, value.length);
textarea.selectionStart = startPos + strToInsert.length;
textarea.selectionEnd = startPos + strToInsert.length;
e.preventDefault();
}
上のコードのポイントは2つある。
1つ目はボタンのクリックを click イベントではなく mousedown としていることである。2つ目は e.preventDefault() で mousedown イベントのデフォルトの挙動を抑制していることだ。
この2つのポイントによって、<textarea> からフォーカスを話すことなく、ボタンのクリックで文字列を挿入できる。

0 件のコメント:
コメントを投稿