JSFiddle - React, Tailwind, and code Playground
HTML
<form action="#">
<textarea name="message" rows="10" cols="30">Insert [firstname] or
[lastname] at the position of the cursor in this textarea while keeping the content already there </textarea>
<br>
<div id="tag_container">
<div class="tag">
<p>[firstname]</p>
</div>
<div class="tag">
<p>[lastname]</p>
</div>
</div>
<input type="submit">
</form>
CSS
#tag_container {
width: 100%;
min-height: 10px;
height: auto;
float: left;
/*background-color: yellow;*/
}
.tag {
width: 100px;
min-height: 10px;
height: auto;
float: left;
/* border: 1px solid red;*/
}
JavaScript
jQuery.fn.extend({
insertAtCaret: function(myValue){
return this.each(function(i) {
if (document.selection) {
//For browsers like Internet Explorer
this.focus();
sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
else if (this.selectionStart || this.selectionStart == '0') {
//For browsers like Firefox and Webkit based
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
} else {
this.value += myValue;
this.focus();
}
})
}
});
/*
$("p").click(function() {
$("textarea").insertAtCaret('text');
*/
$("p").click(function() {
$(this).
$("textarea").insertAtCaret('text');
});