Skip to content

Instantly share code, notes, and snippets.

@Aterbonus
Last active September 13, 2016 07:37
Show Gist options
  • Select an option

  • Save Aterbonus/c103e0f0c9ecdaf56f50533082f783d6 to your computer and use it in GitHub Desktop.

Select an option

Save Aterbonus/c103e0f0c9ecdaf56f50533082f783d6 to your computer and use it in GitHub Desktop.
jQuery stuff to make life a little better
//Fired when enter is pressed
//$('input').onEnter(doStuff);
$.fn.onEnter = function (func) {
return this.each(function (index, element) {
var $element = $(element);
$element.on('keyup', function(e) {
if (e.keyCode == 13) func.apply($element, [e]);
});
});
};
//Insert text where the caret is. Replaces the selected text
//$('input').insertOnCaret('Text to insert');
$.fn.insertOnCaret = function (value) {
return this.each(function (index, element) {
var caretPosition = element.selectionStart;
var selectionEnd = element.selectionEnd;
var oldText = element.value;
element.value = oldText.substr(0, caretPosition) + value + oldText.substr(selectionEnd);
element.selectionStart = caretPosition + value.length;
element.selectionEnd = element.selectionStart;
});
};
//Deletes things where caret is. The number of characters deleted is equal to 'value' (Default 1 to left).
//The direction in which the text is deleted varies if value is positive (right) or negative (left).
//$('input').deleteOnCaret(2);
$.fn.deleteOnCaret = function (value) {
return this.each(function (index, element) {
var caretPosition = element.selectionStart;
var selectionEnd = element.selectionEnd;
var oldText = element.value;
value = value || -1;
element.value = oldText.substr(0, caretPosition + (value < 0 ? value : 0)) + oldText.substr(selectionEnd + (value > 0 ? value : 0));
element.selectionStart = caretPosition + (value < 0 ? value : 0);
element.selectionEnd = element.selectionStart;
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment