Created
May 24, 2011 14:37
-
-
Save Luke-23ae/988822 to your computer and use it in GitHub Desktop.
Prototype Class allowing to insert tab-characters in form-elements
This file contains 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
/** | |
* Usage: new Tabkey('id_of_form_element'); | |
*/ | |
var Tabkey = Class.create({ | |
initialize: function(element) { | |
this.observeInput(element); | |
}, | |
observeInput: function(element) { | |
$(element).observe('keydown', function(e){ | |
if (e.keyCode == Event.KEY_TAB){ | |
e.stop(); | |
this.insertTab(element); | |
} | |
}.bind(this)); | |
}, | |
insertTab: function(element) { | |
element = $(element); | |
if (element.setSelectionRange) { | |
var tabString = String.fromCharCode(9), | |
selectionStart = element.selectionStart, | |
selectionEnd = element.selectionEnd; | |
element.value = element.value.substring(0, selectionStart)+ tabString + element.value.substring(selectionEnd); | |
if (selectionStart != selectionEnd){ | |
this.setSelectionRange(element, selectionStart, selectionStart + element.length); | |
}else{ | |
this.setSelectionRange(element, selectionStart + tabString.length, selectionStart + tabString.length); | |
} | |
} else if (document.selection) { | |
var range = document.selection.createRange(); | |
if (range.parentElement() == element) { | |
var isCollapsed = range.text == ''; | |
range.text = tabString; | |
if (!isCollapsed) { | |
range.moveStart('character', -tabString.length); | |
range.select(); | |
} | |
} // if (range.parentElement ..) | |
} // else if (document.selection) | |
}, // insertTab | |
setSelectionRange: function(element, selectionStart, selectionEnd) { | |
if (element.setSelectionRange) { | |
element.focus(); | |
element.setSelectionRange(selectionStart, selectionEnd); | |
} | |
else if (element.createTextRange) { | |
var range = element.createTextRange(); | |
range.collapse(true); | |
range.moveEnd('character', selectionEnd); | |
range.moveStart('character', selectionStart); | |
range.select(); | |
} | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment