Skip to content

Instantly share code, notes, and snippets.

@philsinatra
Created February 12, 2013 14:57
Show Gist options
  • Save philsinatra/4770421 to your computer and use it in GitHub Desktop.
Save philsinatra/4770421 to your computer and use it in GitHub Desktop.
A CodePen by Phil Sinatra. Insert @ Caret - Insert some html text or in this case an HTML entity at the cursor location in an input.
<div id="symbolsetter">
<table>
<tr>
<td><input type="button" name="sym-copy" onclick="insertSymbol('copy')" value="&copy;" /></td>
</tr>
<tr>
<td><input type="button" name="sym-reg" onclick="insertSymbol('reg')" value="&reg;" /></td>
</tr>
<tr>
<td><input type="button" name="sym-trade" onclick="insertSymbol('trade')" value="&trade;" /></td>
</tr>
</table>
</div>
<hr />
<input type="text" size="50" name="heading_title" id="heading_title" value = "" placeholder="Title" />
// http://www.scottklarr.com/topic/425/how-to-insert-text-into-a-textarea-where-the-cursor-is/
function insertAtCaret(areaId,text) {
var txtarea = document.getElementById(areaId);
var scrollPos = txtarea.scrollTop;
var strPos = 0;
var br = ((txtarea.selectionStart || txtarea.selectionStart == '0') ?
"ff" : (document.selection ? "ie" : false ) );
if (br == "ie") {
txtarea.focus();
var range = document.selection.createRange();
range.moveStart ('character', -txtarea.value.length);
strPos = range.text.length;
}
else if (br == "ff") strPos = txtarea.selectionStart;
var front = (txtarea.value).substring(0,strPos);
var back = (txtarea.value).substring(strPos,txtarea.value.length);
txtarea.value=front+text+back;
strPos = strPos + text.length;
if (br == "ie") {
txtarea.focus();
var range = document.selection.createRange();
range.moveStart ('character', -txtarea.value.length);
range.moveStart ('character', strPos);
range.moveEnd ('character', 0);
range.select();
}
else if (br == "ff") {
txtarea.selectionStart = strPos;
txtarea.selectionEnd = strPos;
txtarea.focus();
}
txtarea.scrollTop = scrollPos;
}
function insertSymbol (whichOne) {
insertAtCaret(focusID, '&' + whichOne + ';')
}
// setup a listener for the focus of any input elements
var focusID;
$(":input").focus(function () {
focusID = this.id;
});
input[type="button"] {
font-size: 1.5em;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment