User:Gerbrant/edit/selection.js

From Wikipedia, the free encyclopedia

Note: After saving, you have to bypass your browser's cache to see the changes. In Internet Explorer and Firefox, hold down the Ctrl key and click the Refresh or Reload button. Opera users have to clear their caches through Tools→Preferences, see the instructions for Opera. Konqueror and Safari users can just click the Reload button.

module("Gerbrant.edit.selection", new function()
{
	if(document.selection && !is_gecko) // IE
		this.replaceTextareaSelection = function(t, f)
		{
			t.focus();
			var r = document.selection.createRange()
			var selText = r.text;
			if(f) r.text = f(selText);
			return selText;
		}
	else // Others
		this.replaceTextareaSelection = function(t, f)
		{
			var start = t.selectionStart;
			if(start == undefined) (function(m)
			{
				alert(m);
				throw new Error(m);
			})("Can't access the selection in textareas because your browser neither supports document.selection for this, nor does it support selectionStart and selectionEnd.");
			var end = t.selectionEnd;
			var text = t.value;
			var selText = text.substring(start, end);
			if(f)
			{
				var scrollTop = t.scrollTop;
				var newText = f(selText);
				t.value = text.substring(0, start) + newText + text.substring(end);
				t.scrollTop = scrollTop;
				t.selectionEnd = (t.selectionStart = start) + newText.length;
				setTimeout(function()
				{
					t.selectionEnd = (t.selectionStart = start) + newText.length;
				}, 0);
			}
			return selText;
		}
	this.replaceSelection = function(f)
	{
		return this.replaceTextareaSelection(document.getElementById("wpTextbox1"), f);
	}
});