Skip to content

Instantly share code, notes, and snippets.

@Korko
Last active May 11, 2021 21:26
Show Gist options
  • Save Korko/3858671 to your computer and use it in GitHub Desktop.
Save Korko/3858671 to your computer and use it in GitHub Desktop.
Focus in a textarea in a specific position
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="jquery.focus.js"></script>
<script type="text/javascript">
function showTextarea() {
var rawContent = 'a § b';
var rawCursorPosition = rawContent.indexOf('§');
rawContent = rawContent.replace('§', '');
if ($('#textarea').is(':visible')) {
$('#textarea').hide();
} else {
$('#textarea').val(rawContent).show().focusOnPos(rawCursorPosition);
console.debug($('#textarea').getFocusPos());
setTimeout(function() {
$('#textarea').insertOnFocus('c');
}, 2000);
}
}
</script>
</head>
<body>
<a href="#" style="display: block;" onclick="showTextarea(); return false;">Show/Hide</a>
<textarea id="textarea" style="display: none"></textarea>
</body>
</html>
jQuery.fn.extend({
getFocusPos: function() {
if (document.selection) { // IE
var sel = document.selection.createRange();
var stored_range = sel.duplicate();
stored_range.moveToElementText(this[0]);
stored_range.setEndPoint('EndToEnd', sel);
return stored_range.text.length - sel.text.length;
} else if (this[0].selectionStart) { // FF/Chrome
return this[0].selectionStart;
}
},
focusOnPos: function(pos) {
jQuery.each(this, function(i, obj) {
if (this.createTextRange) { // IE
var range = this.createTextRange();
range.move("character", pos);
range.select();
} else if (this.setSelectionRange) { // FF/Chrome
this.focus();
this.setSelectionRange(pos, pos);
} else { // Default
this.focus();
}
});
},
insertOnFocus: function(content) {
jQuery.each(this, function(i, obj) {
if (document.selection) { // IE
var sel = document.selection.createRange();
sel.text = content;
} else if (this.selectionStart !== undefined) { // FF/Chrome
var pos = this.selectionStart;
this.value = this.value.substring(0, pos) + content + this.value.substring(pos);
jQuery(this).focusOnPos(pos + content.length);
} else { // Default
this.value += content;
}
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment