Jump to content

User:V111P/js/Templates/Textarea1.js

From Wikipedia, the free encyclopedia
Note: After saving, you have to bypass your browser's cache to see the changes. Google Chrome, Firefox, Microsoft Edge and Safari: Hold down the ⇧ Shift key and click the Reload toolbar button. For details and instructions about other browsers, see Wikipedia:Bypass your cache.
(function () {
	"use strict";

	// CHANGE THIS! It must be a unique id on the page, so make sure it's not something trivial either.
	var buttonId = 'myToolButton'; // the id of the toolbar button

	if ( $.inArray( mw.config.get( 'wgAction' ), ['edit', 'submit'] ) == -1 )
		return;	 // abort if not currently editing an article
 
	mw.loader.using('jquery.textSelection'); // seems to be loaded by default, but just in case

	// This is the script that adds the toolbar button for your script above the textarea
	var addToolbarButtons_scriptUrl = '//en.wikipedia.org/w/index.php?title='
		+ 'User:V111P/js/addToolbarButtons.js&action=raw'
		+ '&ctype=text/javascript'; // [[User:V111P/js/addToolbarButtons.js]]

	// see User:V111P/js/addToolbarButtons for information on how to customize your button
	// you should at least change the icon and the tooltip
	var toolbarButtonProps = {
		id: buttonId,
		tooltip: 'My Tool\'s Tooltip',
		section: 'main',
		group: 'insert',
		callback: myFunction
	};

	if (mediaWiki.libs.addToolbarButtons)
		mediaWiki.libs.addToolbarButtons(toolbarButtonProps); // addToolbarButtons.js already loaded
	else {
		// When it is first loaded, addToolbarButtons.js looks in the array window.toolbarButtonsToAdd
		//  to determine which buttons to create. First we create the array if it doesn't exist, then
		//  we add our button properties to it. Then we call $.ajax to load addToolbarButtons.js
		var tbs = window.toolbarButtonsToAdd = window.toolbarButtonsToAdd || [];
		tbs.push(toolbarButtonProps);
		$.ajax( { url: addToolbarButtons_scriptUrl, dataType: 'script', cache: true } );
	}

	var textArea = $('#wpTextbox1');

	// The function called when the toolbar button is pressed.
	// The name of this function must match the value of the callback property
	//  of the toolbarButtonProps object above.
	function myFunction() {
		var sel = textArea.textSelection('getSelection');
		sel = sel.replace(/\r/g, ''); // IE before 9 doesn't remove the \r's

		// manipulate the text in the sel variable
		sel = sel.replace(/ /g, '_'); // this is an example. Replaces all spaces with underscores

		// replace the selected text in the textarea with the new text
		textArea.textSelection('encapsulateSelection', {pre: sel, replace: true});
	}

})();