User:Gerbrant/edit/selection.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump. This code will be executed when previewing this page. |
Documentation for this user script can be added at User:Gerbrant/edit/selection. |
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);
}
});