Advertisement
skyboy

Advanced Tab Catch

May 28th, 2011
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function setSelectionRange(input,selectionStart,selectionEnd){if(input.setSelectionRange){input.focus();input.setSelectionRange(selectionStart,selectionEnd);}else if(input.createTextRange){var range=input.createTextRange();range.collapse(true);range.moveEnd('character',selectionEnd);range.moveStart('character',selectionStart);range.select();}}
  2. function replaceSelection(input, replaceString, shift) {
  3.     var ie = false;
  4.     var value = input.value;
  5.     if (input.setSelectionRange) {
  6.         var selectionStart = input.selectionStart;
  7.         var selectionEnd = input.selectionEnd;
  8.         var old = value.substring(selectionStart, selectionEnd);
  9.     } else if(document.selection) {
  10.         ie = true;
  11.         var range=document.selection.createRange();
  12.         if (range.parentElement() == input) {
  13.             var selectionStart = input.selectionStart;
  14.             var selectionEnd = input.selectionEnd;
  15.             var old = range.text;
  16.         } else return;
  17.     }
  18.     var isCollapsed = old == '';
  19.     if (!isCollapsed && replaceString == '\t' && (old.indexOf('\n') != -1 || ((!selectionStart || value.charCodeAt(selectionStart - 1) == 10) && (selectionEnd == value.length || value.charCodeAt(selectionEnd) == 10)))) {
  20.         if (selectionStart) selectionStart = value.substring(0, selectionStart + 2).lastIndexOf('\n') + 1 || selectionStart;
  21.         selectionEnd = (value.indexOf('\n', selectionEnd) + 1 || value.length + 1) - 1;
  22.         old = value.substring(selectionStart, selectionEnd).split("\n");
  23.         var i = old.length, a;
  24.         if (!shift) while (i--) {
  25.             a = old[i];
  26.             if (a) old[i] = '\t' + a;
  27.         }
  28.         else while (i--) {
  29.             a = old[i];
  30.             if (a) old[i] = (a.charCodeAt(0) == 9 ? a.substr(1) : a);
  31.         }
  32.         replaceString = old.join('\n');
  33.     }
  34.     if (ie) {
  35.         range.text = replaceString;
  36.         if (isCollapsed) return;
  37.     } else {
  38.         input.value = value.substring(0, selectionStart) + replaceString + value.substr(selectionEnd);
  39.     }
  40.     var end = selectionStart + replaceString.length;
  41.     setSelectionRange(input, (selectionStart != selectionEnd) ? selectionStart : end, end);
  42. }
  43. function stopEvent(e){if(e.preventDefault){e.preventDefault();}if(e.stopPropagation){e.stopPropagation();}e.stopped=true;}
  44. function catchTab(item,e){if(!e)e=window.event;var c=e.keyCode||e.which;if(c==9){var scrollCurrent=item.scrollTop;replaceSelection(item,String.fromCharCode(9),e.shiftKey);stopEvent(e);item.scrollTop=scrollCurrent;return false;}}
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement