Last active
September 13, 2016 07:37
-
-
Save Aterbonus/c103e0f0c9ecdaf56f50533082f783d6 to your computer and use it in GitHub Desktop.
jQuery stuff to make life a little better
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //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