// shortcut hvarh=mw.html;varmyElement=h.element('div',// tagName{},// attributes// content:newh.Raw(// We don't want to escape the return of h.element(), instead add it raw// Without this the result would be '<div>&lt;img src=&quot;&amp;lt;&quot;/&gt;</div>'h.element('img',// tagName{src:'<'}// attributes)));// myElement is '<div><img src="&lt;"/></div>' (as a string)

Note that loading the mediawiki.jqueryMsg module significantly changes the behavior of this module. See above link.

Returns a new instance of Message. mediaWiki.msg() is a shortcut to this with output using the text format (however, without jqueryMsg, this is equivalent to the plain format). See Localisation#Using messages in JavaScript for information about using PLURAL, GENDER, and more advanced message features in JavaScript.

key

Key of the message

parameter_1

(optional) this argument and any later ones will be passed to the Message constructor as the parameter array (to do replaces for $1, $2 etc.)

/** * Suppose we have a message key "user-welcome" with value * "Hello $1. Welcome to $2. Last visit by $1: $3". */// Get instance of Messagevarwelcome=mw.message('user-welcome','Krinkle','Wikipedia','now');// Get it as a plain string (other formats are 'text', 'parse', and 'escaped')welcome.format='plain';welcome.toString();// Shortcut for the abovewelcome.plain();// Returns: "Hello Krinkle. Welcome to Wikipedia. Last visit by Krinkle: now"

Since MW 1.19r93247 Keep track of origin in the client-side registry of ResourceLoader by adding an internal source id (lowercase a-z string, first parameter) for a given loadscript property (second parameter). The internal registry will have an origin-key for each module (just like it has for groups). The execute-function will use the right loader-script as needed. And split up requests per module source.

Loads modules and other sources. It can be called with one or more modules by name. It can also load an external script or style URI beginning with either "http://", "https://" or "//" and a mime-type in the second argument (either "text/css" or "text/javascript"). If no mime-type is provided, "text/javascript" is assumed. mw.loader.load creates an asynchronous request, so if you need to run code that depends on a module, use mw.loader.using instead. If you want to load another script use jquery.getScript.

// Load one module by name. Will make 1 http request loading all JS, CSS of this and its dependencies. Will also load any needed interface messages to the memory of mw.msgmw.loader.load('jquery.ui.datepicker');// Will do all resources stuff for multiple modules at oncemw.loader.load(['jquery.ui.dialog','jquery.hoverIntent','mediawiki.foobar']);// Load an external javascript file as ismw.loader.load('//www.mediawiki.org/w/index.php?title=MediaWiki:Gadget-UTCLiveClock.js&action=raw&ctype=text/javascript&smaxage=21600&maxage=86400');// Load an external stylesheet as ismw.loader.load('http://example.com/mystyles.css?color=blue','text/css');

using can be called with two or three arguments (dependencies, function to execute when modules are successfully loaded, function on error). The error function takes two arguments, the error, and an array of dependencies that caused it.

mw.loader.using('jquery.colorUtil',function(){varcurColor,newColor;// This function wil be called right away if the required modules are already loaded// Otherwise the module(s) are loaded and if all succesfull, the function is calledcurColor='rgb(70,140,210)';newColor=$.colorUtil.getColorBrightness(curColor,+0.2);alert('20% brigher than '+curColor+' is '+newColor);});

This is is automatically loaded (only) in debug-mode (can be enabled with debug=true in the URL) and is an alternative to calling console.log() which would cause errors in browsers that don't have a console or don't have it enabled.

Calling this either pushes the messages to console if its available and have a logging facility, or adds it to an #mw-log-console if not (the element is created on the first call)

mw.log('To be logged message here');

Note that different browsers and extensions may enable or disable different consoles and different logging facilities, and that they may or may not be visible even if they are used for logging purposes.

A reusable class to store, get and set a set of variables.
The core uses this for mw.config and mw.user.options

When making an instance the function takes one parameter which affects whether the set will be made globally available (ie. as items of window) or local.
By default this is false (not global) and will thus not not overwrite any global variables with the same name.

.values

An object containing all the variables. If 'global' was true during initialization, this is an alias to the window object.

.exists(key)

Function returns true if an entry with the key(s) exists, false otherwise

.get(key, fallback)

Returns the value of the key(s) or (optionally) the value of the second argument if the key does not exist (returns null if it doesn't exist and no fallback was provided)

.set(key, value)

Creates / Modifies one or multiple values

Examples

// Create a new mapvarmyMap=newmw.Map();// Set a few valuesmyMap.set({'name':'John Doe','age':19,'planet':'Earth','address':'Wikistreet 7, New York'});// Set one more valuemyMap.set('spouse','Jane Jackson');// Do something if a value is setif(myMap.exists('address')){alert('This map does have a value for "address". It is: '+myMap.get('address'));}else{alert('This map does not have a value for "address".');}// Get multiple valuesvarNameAgeBirth=myMap.get(['name','age','birthdate']);// NameAgeBirth.name is 'John Doe'// NameAgeBirth.age is 19// NameAgeBirth.birthdate is null

Address Book example

// Create a new map for thisvarmyAddressBook=newmw.Map();// Define an object with name / address combinations// This data could be coming from an AJAX request and/or from a databasevaraddresses={'John Doe':'Wikistreet 7, New York','Jane Jackson':'Oxfordstreet 21, London','Max Heinz':'Rote strasse 201, Berlin'}// Set the variables in the addressbookmyAddressBook.set(addresses);// A request could come in for a few namesvarwantedNames=['Max Heinz','George Johnson','Jane Jackson'];// Check if they all have an entryif(!myAddressBook.exists(wantedNames)){alert('One or more names do not have a known address');// In our example, there is no address for George Johson}wantedData=myAddressBook.get(wantedNames,'<em>Unknown location</em>');// wantedData['Jane Jackson'] is 'Oxfordstreet 21, London' // wantedData['George Johnson'] is '<em>Unknown location</em>'

Function returns the username if the user is logged in, or returns sessionId if the user is anonymous.
Note this does not return the user's numeric ID in the wiki (which is available as a configuration value).

Prior to MediaWiki 1.22 the "id" for anonymous users was retained across sessions by a long-term cookie (bug 44327).

When called for the first time generates a sessionId and sets a domain-wide cookie and returns the sessionId.
When it's set already (ie. after calling it, or when it was set earlier this session on another page) returns just the sessionId.

Contains the preferences of the user, or the defaults when logged out. (mw.user.options is an instance of the mw.Map constructor)

// Get a preference option and use it directlyalert('According to the preferences, your gender is '+mw.user.options.get('gender'));// Get several preferences and compare them with $.compareObjectif($.compareObject(mw.user.options.get(['diffonly','showhiddencats']),{diffonly:0,showhiddencats:0})){// User's preferences match the object}else{// User's preferences don't match the given set}

This module sets the mw.Api constructor. The main methods of the mw.Api object are get, post, and ajax. The mediawiki.api module (and its plugins) return a promise. This is just like jQuery.ajax (and its derivatives such as jQuery.get, jQuery.post and jQuery.getJSON).

A promise provides three important methods that can be used to register a callback: done(), fail() and always(). In general you should always either have the first two or the latter.

The base mediawiki.api plugin provides two methods that take a raw API query:

There are various plugins (other modules depending on this one) for this module that make it more convenient to use certain API actions actions by abstracting the input and output. The ones in core are listed below.

Adds a <style> element to the HEAD and returns the CSSStyleSheet object.

The CSSStyleSheet object can be used to disable the css rules at any later time and re-enable them as well.
This can be done through the 'disabled' attribute. When setting this to true, the rules no longer apply.
When setting to false, the rules apply again.

// Add a simple stylesheet rulemw.util.addCSS('.plainlinks { color: green; }');// Add a rule and set a variable to the sheetvarmyCssRules=mw.util.addCSS('.plainlinks { color: green; }');$('#myButton').click(function(){// When button is clicked, toggle the stylesheet from true to non-true (false), or from false to non-false (true) myCssRules.disabled=!myCssRules.disabled;});

A jQuery object for a page's overall content area regardless of the skin used. This is, for example, #content in the Vector-skin (before 1.20 it was #bodyContent). This variable is initialized from the mediawiki.page.startup module. Make sure to either add it to your dependencies or wrap it inline in mw.loader.using( 'mediawiki.page.startup', ... );

This does not refer to the area where the page content goes. If you wish to work with that area of the page instead of the overall content area you should use $('#mw-content-text') instead.

/* Add some HTML to the page content */mw.util.$content.append('<h2>Lorem ipsum</h2><p>This section was just added to the bottom of the wiki page.</p>');/* Count number of tables in the page's content with a class of "wikitable" */var$wikitablesInPage=mw.util.$content.find('table.wikitable');if($wikitablesInPage.length){alert('There are '+$wikitablesInPage.length+' wikitables on this page.');}else{alert('There are no wikitables on this page.');}

Here is a more advanced example involving loading in extra content with an AJAX request.
Run this example on a page other than the main page.

/* Loads in main page (or any page for that matter) over AJAX (may be useful for Special:BlankPage) */// Put a loading message on top of the pagemw.util.$content.prepend('<p><em>Loading...</em></p><hr/>');// To get the article contents, use #mw-content-text instead.$('#mw-content-text').load(mw.util.wikiGetlink(mw.config.get('wgMainPageTitle'))+' #mw-content-text',function(){mw.notify('Load complete!');});

This function returns the value of the specified URL parameter.
By default it uses the current window's address. Optionally you can pass it a custom location.

It returns null if the parameter is not present.
Returns an empty string("") if it was an empty parameter (such as /page.php?some=parameter&emptyparameter=&id=12

// Location: https://www.mediawiki.org/w/index.php?title=ResourceLoader/Default_modules&action=edit&section=28// Suppose we're editing a page section, this will return the number of the edit sectionmw.util.getParamValue('section');/* returns '28'; */// Extract a value from a custom url// For example on a diff page where there is: "← Older edit" and you need the oldid of the previous editvaroldid=mw.util.getParamValue('oldid','//www.mediawiki.org/w/index.php?title=ResourceLoader/Default_modules&diff=prev&oldid=365296');if(oldid!==null){alert('The previous text version of this page has id: '+oldid);}else{alert('No "oldid" parameter found in the given address.');}

This function is ported from the legacy wikibits keeping it fully backwards compatible, with a few adjustments and with added support to hide the message by calling with no arguments or when passing null.

// Basic usage, replace/add the message on topmw.util.jsMessage('This is something a <strong>message</strong> for the <strong>user</strong>');// Classed usage, adds/replaces the 'mw-js-message-foobar' as class for the message-boxmw.util.jsMessage('Foobar message 01255','foobar');// Any of the folllowing will empty and hide the boxmw.util.jsMessage();mw.util.jsMessage('');mw.util.jsMessage(null);

This function returns a "pretty" version of a URL encoded wiki page name. It keeps slashes and colons unencoded. The behavior differs from wfUrlencode on the PHP side.

// This url will end up in the user's addressbar, so prettification is useful.var$histLink=$('<a>').attr('href',mw.config.get('wgScript')+'?action=history&title='+mw.util.wikiUrlencode(mw.config.get('wgPageName')),);// This will never be shown, don't bother with string concatenation, just encode it regularly with $.param(), much easier.jQuery.ajax({url:mw.config.get('wgScript')+'?'+$.param({action:'history',title:mw.config.get('wgPageName')}),dataType:'html'}).done(function(html){/* .. */});

varuri=newmw.Uri();// This throws the following error on 1.19.1: 'Bad constructor arguments'uri;// Instance for the location of the current windowvarotheruri=newmw.Uri('http://mediawiki.org/');// The trailing slash is *required*otheruri.toString();// "http://mediawiki.org"

mw.notify('This is a notification.');// Send a plaintext notificationmw.notify(mw.message('some-message'));// Use an i18n message to send a notificationmw.notify($('<span>This is a <u>HTML</u> notification.</span>'));// Send a html notification with a jQuery instance (a DOM node also works)mw.notify('Test',{title:'Title!'});// Give the notification a titlemw.notify('Test',{autoHide:false});// Don't automatically hide the notificationmw.notify('Test',{tag:'foobar'});// Send a notification tagged with a tagmw.notify('Test 2',{tag:'foobar'});// This one will replace the previous 'foobar' notification.

This is a jQuery module that allows you to put a red "badge" on an item on the page. 'Badge' in this case should be considered a verb rather than a noun, as the function returns the parent, not the badge itself.

This single-function plugin can be called to add this functionality to any number of checkboxes.
By default (onload) it's applied to all input elements that have a type of checkbox, excluding any with a class of 'noshiftselect'. As it has a built-in prevention to avoid binding the CheckboxShiftClick twice to the same element you can simply run the line below under "Default" again at any time if you want to enable dynamically added checkboxes in the page to be shift-selectable as well.
Or alternatively run it on the specific selector of choice (see second example below).

// Default:$('input[type=checkbox]:not(.noshiftselect)').checkboxShiftClick();// Enable the functionality for checkboxes in dynamically created form <form id="my-tool-form">$('form#my-tool-form input[type=checkbox]').checkboxShiftClick();

A plugin that extracts information about the client's browser, layout engine and operating system. Use this instead of jQuery.browser, which is deprecated and will be removed from jQuery in the near future.

The profile function is the main function here and returns (and caches) all the information in an object in. All possible values (except for version numbers) are predefined. A typical return looks like this:

if($.client.profile().layout=='gecko'&&$.client.profile().platform=='linux'){// This will only run on Gecko browsers (ie. Mozilla Firefox) on Linux.}if($.client.profile().name=='msie'){// Only for good ol' Internet Explorer}// Shortcutvarprof=$.client.profile();if(prof.name=='firefox'&&prof.versionBase=='2'&&prof.platform=='win'){// Target Mozilla Firefox 2.x on Windows}

varkey="myStorageKey",value=$.jStorage.get(key);if(!$.jStorage.storageAvailable()){thrownewError('No storage available. Fall back to ... or tell the user to install a real browser!');}$.jStorage.listenKeyChange(key,function(key,action){if(window.console&&$.isFunction(console.log)){console.log(key+" has been "+action);}});value={a:1,b:2,c:[3,4,5]};$.jStorage.set(key,value);

Plugin makes all passed elements collapsible. It supports lots of variations such as:

Simple

Add "mw-collapsible" to an element (a <div> for example) with some content and save the page. The inner content of this element will be treated as collapsible content. Prepended to the element, before the collapsible content, is a toggle-link with a localized label (collapsible-expand, collapsible-collapse)

Initial state

Adding '"mw-collapsed'" as additional class will cause the element to be initially collapsed when the page is loaded.

Custom label

HTML5 only Using the data-collapsetext and data-expandtext attributes one can define a custom text for the toggle labels added by the script. When added in wikitext these could populated by a localized message like:<divclass="mw-collapsible"data-expandtext="{{int:show}}"data-collapsetext="{{int:hide}}">

Remote toggle

If you don't want the script to put the default toggle link (wether or not with a custom label) in your element, you can make one of your own. This could reside anywhere inside or outside the collapsible element. It's relationship to the collapsible element is detected by using ID attributes with the prefix mw-customcollapsible and mw-customtoggle for the collapsible element and the togglelink respectively.

This plugin adds support for placeholder texts in input fields for browsers that don't support the HTML5 attribute yet. If the attribute is not supported it's applied to all input elements with a 'placeholder' attribute, on-load.

It has a built-in check for browser support, but for efficiency it's best to do this check (also) wrapped around to call.

There are several methods added to the jQuery object for older browsers serving as backwards-compatibility for new native prototypes in newer browser. Also several other convenience functions have been created such as isEmpty and escapeRE. In MediaWiki 1.17 and 1.18 these methods were part of the "jquery.mwPrototypes" module. In MediaWiki 1.19 this module was renamed to "jquery.mwExtension" (see rev:94227).