User:Joeytje50/tabkey.js

/* This script allows the tab key to be used in editboxes, by default only on .js and .css pages in the user and mediawiki namespaces, but if you want you can add this above the import of this script: var tabKeyEnable = (statement); replacing statement with the statement that enables the tab key. For example, this enables the tabinsert on all MediaWiki pages: var tabKeyEnable = (wgCanonicalNamespace=="MediaWiki"); and this enables the tabinsert on all pages: var tabKeyEnable = true;

/*** First the required functions ***/

// http://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript String.prototype.replaceAt=function(index, char) { return this.substr(0, index) + char + this.substr(index+char.length); }

// http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/ function getCaretPos(ctrl) { var CaretPos = 0;   // IE Support if (document.selection) { ctrl.focus ; var Sel = document.selection.createRange ; Sel.moveStart ('character', -ctrl.value.length); CaretPos = Sel.text.length; }   // Firefox support else if (ctrl.selectionStart || ctrl.selectionStart == '0') CaretPos = ctrl.selectionStart; return (CaretPos); } function setCaretPos(ctrl, pos){ if(ctrl.setSelectionRange) {       ctrl.focus; ctrl.setSelectionRange(pos,pos); }   else if (ctrl.createTextRange) { var range = ctrl.createTextRange; range.collapse(true); range.moveEnd('character', pos); range.moveStart('character', pos); range.select; } }

/*** The script ***/

var tabKeyEnabled = (typeof tabKeyEnabled == 'undefined')?(wgAction=='edit'||wgAction=='submit')&&wgTitle.match(/\.\w\w\w?$/):tabKeyEnabled; if (tabKeyEnabled) { document.getElementById('wpTextbox1').onkeydown = function(e) { if (e.keyCode == 9) { e.preventDefault; var caretPos = getCaretPos(this) this.value = this.value.replaceAt(caretPos, this.value.charAt(caretPos) + '\t'); setCaretPos(this, caretPos+1); return false; }	} }