jQueryPlugins

MediaWiki includes the jQuery library. This is extended by a series of plugins.

This page documents the list of jQuery plugins that can be used on a jQuery object. When using them please pay attention to their installation instructions.

Methods

byteLimit(limit, filterFunction) → {jQuery}static #

Enforces a byte limit on an input field, assuming UTF-8 encoding, for situations when, for example, a database field has a byte limit rather than a character limit. Plugin rationale: Browser has native maxlength for number of characters (technically, UTF-16 code units), this plugin exists to limit number of bytes instead.

Can be called with a custom limit (to use that limit instead of the maxlength attribute value), a filter function (in case the limit should apply to something other than the exact input value), or both. Order of parameters is important!

Parameters:

Name Type Attributes Description
limit number optional

Limit to enforce, fallsback to maxLength-attribute, called with fetched value as argument.

filterFunction function optional

Function to call on the string before assessing the length.

Source:

Returns:

Type
jQuery

Enforces a byte limit on an input field, assuming UTF-8 encoding, for situations when, for example, a database field has a byte limit rather than a character limit.

codePointLimit(limit, filterFunction) → {jQuery}static #

Enforces a codepoint (character) limit on an input field.

For unfortunate historical reasons, browsers' native maxlength counts the number of UTF-16 code units rather than Unicode codepoints, which means that codepoints outside the Basic Multilingual Plane (such as many emojis) count as 2 characters each. This plugin exists to correct this.

Can be called with a custom limit (to use that limit instead of the maxlength attribute value), a filter function (in case the limit should apply to something other than the exact input value), or both. Order of parameters is important!

Parameters:

Name Type Attributes Description
limit number optional

Limit to enforce, fallsback to maxLength-attribute, called with fetched value as argument.

filterFunction function optional

Function to call on the string before assessing the length.

Source:

Returns:

Type
jQuery
Enforces a codepoint (character) limit on an input field.

confirmable(options)static #

Enable inline confirmation for given clickable element (like <a /> or <button />). Provided by the jquery.confirmable ResourceLoader module.

An additional inline confirmation step being shown before the default action is carried out on click.

Calling .confirmable( { handler: function () { … } } ) will fire the handler only after the confirmation step.

The element will have the jquery-confirmable-element class added to it when it's clicked for the first time, which has white-space: nowrap; and display: inline-block; defined in CSS. If the computed values for the element are different when you make it confirmable, you might encounter unexpected behavior.

Example

mw.loader.using( 'jquery.confirmable' ).then( () => {
      $( 'button' ).confirmable();
} );

Parameters:

Name Type Attributes Description
options Object optional
Properties:
Name Type Attributes Default Description
events string optional
'click'

Events to hook to.

wrapperCallback function optional

Callback to fire when preparing confirmable interface. Receives the interface jQuery object as the only parameter.

buttonCallback function optional

Callback to fire when preparing confirmable buttons. It is fired separately for the 'Yes' and 'No' button. Receives the button jQuery object as the first parameter and 'yes' or 'no' as the second.

handler function optional

Callback to fire when the action is confirmed (user clicks the 'Yes' button).

delegate string optional

Optional selector used for jQuery event delegation

i18n string optional

Text to use for interface elements.

Properties:
Name Type Attributes Default Description
space string optional
' '

Word separator to place between the three text messages.

confirm string optional
'Are you sure?'

Text to use for the confirmation question.

yes string optional
'Yes'

Text to use for the 'Yes' button.

no string optional
'No'

Text to use for the 'No' button.

yesTitle string optional

Optional title text to use for the 'Yes' button.

noTitle string optional

Optional title text to use for the 'No' button.

Source:
Enable inline confirmation for given clickable element (like <a /> or <button />).

cookie(key, value, options) → {string|Object}static #

Set a cookie.

Example

mw.loader.using( 'mediawiki.cookie' ).then( () => {
    $.cookie( 'name', 'value', {} );
} );

Parameters:

Name Type Attributes Description
key string optional

Cookie name or (when getting) omit to return an object with all current cookie keys and values.

value string | null optional

Cookie value to set. If null, this method will remove the cookie. If omited, this method will get and return the current value.

options mw.cookie.CookieOptions optional
Source:

Returns:

The current value (if getting a cookie), or an internal document.cookie expression (if setting or removing).

Type
string | Object
Set a cookie.

goIn(instantToggle) → {jQuery}static #

jQuery plugin to fade or snap to visible state.

Parameters:

Name Type Attributes Default Description
instantToggle boolean optional
false
Source:

Returns:

Type
jQuery
jQuery plugin to fade or snap to visible state.

goOut(instantToggle) → {jQuery}static #

jQuery plugin to fade or snap to hiding state.

Parameters:

Name Type Attributes Default Description
instantToggle boolean optional
false
Source:

Returns:

Type
jQuery
jQuery plugin to fade or snap to hiding state.

highlightText(matchString, options) → {jQuery}static #

Highlight certain text in current nodes (by wrapping it in <span class="highlight">...</span>). Provided by the jquery.highlightText ResourceLoader module.

Example

mw.loader.using( 'jquery.highlightText' ).then( () => {
      // no styling is provided by default.
      mw.util.addCSS( `.highlight { background: yellow; }` )
      $( '#bodyContent' ).highlightText( 'bear' );
} );

Parameters:

Name Type Attributes Description
matchString string

String to match

options Object optional
Properties:
Name Type Attributes Default Description
method string optional
'splitAndHighlight'

Method of matching to use, one of:

  • 'splitAndHighlight': Split matchString on spaces, then match each word separately.
  • 'prefixHighlight': Match matchString at the beginning of text only.
  • 'prefixPlusComboHighlight': Match matchString plus any combining characters at the beginning of text only.
Source:

Returns:

Type
jQuery
Highlight certain text in current nodes (by wrapping it in <span class="highlight">...</span>).

injectSpinner(opts) → {jQuery}static #

Inject a spinner after each element in the collection. Provided by the jquery.spinner ResourceLoader module.

Inserts spinner as siblings (not children) of the target elements. Collection contents remain unchanged.

Example

mw.loader.using( 'jquery.spinner' ).then( () => {
      $( '#bodyContent' ).injectSpinner();
} );

Parameters:

Name Type Attributes Description
opts Object | string optional

See #createSpinner

Source:

Returns:

Type
jQuery
Inject a spinner after each element in the collection.

makeCollapsible(options) → {jQuery}static #

Enable collapsible-functionality on all elements in the collection. Provided by the jquery.makeCollapsible ResourceLoader module.

  • Will prevent binding twice to the same element.
  • Initial state is expanded by default, this can be overridden by adding class "mw-collapsed" to the "mw-collapsible" element.
  • Elements made collapsible have jQuery data "mw-made-collapsible" set to true.
  • The inner content is wrapped in a "div.mw-collapsible-content" (except for tables and lists).

Example

mw.loader.using( 'jquery.makeCollapsible' ).then( () => {
      $( 'table' ).makeCollapsible();
} );

Parameters:

Name Type Attributes Description
options Object optional
Properties:
Name Type Attributes Default Description
collapseText string optional

Text used for the toggler, when clicking it would collapse the element. Default: the 'data-collapsetext' attribute of the collapsible element or the content of 'collapsible-collapse' message.

expandText string optional

Text used for the toggler, when clicking it would expand the element. Default: the 'data-expandtext' attribute of the collapsible element or the content of 'collapsible-expand' message.

collapsed boolean optional

Whether to collapse immediately. By default collapse only if the element has the 'mw-collapsed' class.

$customTogglers jQuery optional

Elements to be used as togglers for this collapsible element. By default, if the collapsible element has an id attribute like 'mw-customcollapsible-XXX', elements with a class of 'mw-customtoggle-XXX' are made togglers for it.

plainMode boolean optional
false

Whether to use a "plain mode" when making the element collapsible - that is, hide entire tables and lists (instead of hiding only all rows but first of tables, and hiding each list item separately for lists) and don't wrap other elements in div.mw-collapsible-content. May only be used with custom togglers.

Source:

Returns:

Type
jQuery
Enable collapsible-functionality on all elements in the collection.

msg(message, …arguments)static #

Parses the message in the message key, doing replacements optionally, and appends the nodes to the current selector. Bindings to passed-in jquery elements are preserved. Functions become click handlers for [$1 linktext] links.

Example

mw.loader.using('mediawiki.jqueryMsg' ).then(() => {
       var $userlink = $( '<a>' ).click( function () { alert( "hello!!" ) } );
       $( 'p#headline' ).msg( 'hello-user', $userlink );
} );

// N.B. replacements are variadic arguments or an array in second parameter. In other words:
somefunction( a, b, c, d )
// is equivalent to
somefunction( a, [b, c, d] )

// Note: We append to 'this', which in a jQuery plugin context will be the selected elements.

Parameters:

Name Type Attributes Description
message string

key

arguments Array.<string> repeatable
Source:

Parses the message in the message key, doing replacements optionally, and appends the nodes to the current selector.

removeCookie(key, options) → {boolean}static #

Remove a cookie by key.

Example

mw.loader.using( 'mediawiki.cookie' ).then( () => {
    $.removeCookie( 'name', {} );
} );

Parameters:

Name Type Description
key string
options mw.cookie.CookieOptions
Source:

Returns:

True if the cookie previously existed

Type
boolean
Remove a cookie by key.

suggestions(options) → {jQuery}static #

This plugin provides a generic way to add suggestions to a text box. Provided by the jquery.suggestions ResourceLoader module.

Set options:

$( '#textbox' ).suggestions( { option1: value1, option2: value2 } ); $( '#textbox' ).suggestions( option, value );

Example

// Initialize:
mw.loader.using( 'jquery.suggestions' ).then(()=> {
 $( '#textbox' ).suggestions();
});

Parameters:

Name Type Description
options Object
Properties:
Name Type Attributes Default Description
fetch function optional

Callback that should fetch suggestions and set the suggestions property. Called in context of the text box.

Properties:
Name Type Description
query string
response function

Callback to receive the suggestions with

Properties:
Name Type Description
suggestions Array
maxRows number
cancel function optional

Callback function to call when any pending asynchronous suggestions fetches. Called in context of the text box.

special Object optional

Set of callbacks for rendering and selecting.

Properties:
Name Type Description
render function

Called in context of the suggestions-special element.

Properties:
Name Type Description
query string
context Object
select function

Called in context of the suggestions-result-current element.

Properties:
Name Type Description
$textbox jQuery
result Object optional

Set of callbacks for rendering and selecting

Properties:
Name Type Description
render function

Called in context of the suggestions-result element.

Properties:
Name Type Description
suggestion string
context Object
select function

Called in context of the suggestions-result-current element.

Properties:
Name Type Description
$textbox jQuery
update Object optional

Set of callbacks for listening to a change in the text input.

Properties:
Name Type Description
before function

Called right after the user changes the textbox text.

after function

Called after results are updated either from the cache or the API as a result of the user input.

$region jQuery optional
this

The element to place the suggestions below and match width of.

suggestions Array.<string> optional

Array of suggestions to display.

maxRows number optional
10

Maximum number of suggestions to display at one time. Must be between 1 and 100.

delay number optional
120

Number of milliseconds to wait for the user to stop typing. Must be between 0 and 1200.

cache boolean optional
false

Whether to cache results from a fetch.

cacheMaxAge number optional
60000

Number of milliseconds to cache results from a fetch. Must be higher than 1. Defaults to 1 minute.

submitOnClick boolean optional
false

Whether to submit the form containing the textbox when a suggestion is clicked.

maxExpandFactor number optional
3

Maximum suggestions box width relative to the textbox width. If set to e.g. 2, the suggestions box will never be grown beyond 2 times the width of the textbox. Must be higher than 1.

expandFrom string optional
auto

Which direction to offset the suggestion box from. Values 'start' and 'end' translate to left and right respectively depending on the directionality of the current document, according to $( document.documentElement ).css( 'direction' ). Valid values: "left", "right", "start", "end", and "auto".

positionFromLeft boolean optional

Sets expandFrom=left, for backwards compatibility.

highlightInput boolean optional
false

Whether to highlight matched portions of the input or not.

Source:

Returns:

Type
jQuery
This plugin provides a generic way to add suggestions to a text box.

tablesorter(settings) → {jQuery}static #

Create a sortable table with multi-column sorting capabilities. Provided by jquery.tablesorter ResourceLoader module.

Example

mw.loader.using( 'jquery.tablesorter' ).then( () => {
     // Create a simple tablesorter interface
     $( 'table' ).tablesorter();

     // Create a tablesorter interface, initially sorting on the first and second column
     $( 'table' ).tablesorter( { sortList: [ { 0: 'desc' }, { 1: 'asc' } ] } )
         .on( 'sortEnd.tablesorter', () => console.log( 'Triggered as soon as any sorting has been applied.' ) );
} );

Parameters:

Name Type Description
settings jQueryPlugins~TableSorterOptions
Source:

Returns:

Type
jQuery
Create a sortable table with multi-column sorting capabilities.

textSelection(command, commandOptions) → {any}static #

Do things to the selection in a <textarea>, or a textarea-like editable element. Provided by the jquery.textSelection ResourceLoader module.

var $textbox = $( '#wpTextbox1' );
$textbox.textSelection( 'setContents', 'This is bold!' );
$textbox.textSelection( 'setSelection', { start: 8, end: 12 } );
$textbox.textSelection( 'encapsulateSelection', { pre: '<b>', post: '</b>' } );
// Result: Textbox contains 'This is <b>bold</b>!', with cursor before the '!'

Example

mw.loader.using( 'jquery.textSelection' ).then( () => {
      const contents = $( 'textarea' ).textSelection( 'getContents' );
} );

Parameters:

Name Type Attributes Description
command string

Command to execute, one of:

  • getContents
  • setContents
  • getSelection
  • replaceSelection
  • encapsulateSelection
  • getCaretPosition
  • setSelection
  • scrollToCaretPosition
  • register
  • unregister
commandOptions any optional

Options to pass to the command

Source:

Returns:

Depending on the command

Type
any
Do things to the selection in a <textarea>, or a textarea-like editable element.

trimByteLength(safeVal, newVal, byteLimit, filterFunction) → {Object|string|boolean}static #

Utility function to trim down a string, based on byteLimit and given a safe start position.

It supports insertion anywhere in the string, so "foo" to "fobaro" if limit is 4 will result in "fobo", not "foba". Basically emulating the native maxlength by reconstructing where the insertion occurred.

Parameters:

Name Type Attributes Description
safeVal string

Known value that was previously returned by this function, if none, pass empty string.

newVal string

New value that may have to be trimmed down.

byteLimit number

Number of bytes the value may be in size.

filterFunction function optional

See jQuery#byteLimit.

Deprecated:
  • Use `require( 'mediawiki.String' ).trimByteLength` instead.
Source:

Returns:

Utility function to trim down a string, based on byteLimit and given a safe start position.

updateTooltipAccessKeys() → {jQuery}static #

Update the titles for all elements in a jQuery selection. Installed by mediawiki.util module.

Example

// Converts tooltip "[z]" to associated browser shortcut key e.g. "[ctrl-option-z]"
mw.loader.using( 'mediawiki.util' ).then( () => {
    var $a = $('<a href="/wiki/Main_Page" title="Visit the main page [z]" accesskey="z"><span>Main page</span></a>');
    $a.updateTooltipAccessKeys();
} );
Source:

Returns:

Type
jQuery
Update the titles for all elements in a jQuery selection.

Type Definitions

TableSorterOptions #

Type:

Properties:

Name Type Attributes Default Description
cssHeader string optional
"headerSort"

A string of the class name to be appended to sortable tr elements in the thead of the table.

cssAsc string optional
"headerSortUp"

A string of the class name to be appended to sortable tr elements in the thead on a ascending sort.

cssDesc string optional
"headerSortDown"

A string of the class name to be appended to sortable tr elements in the thead on a descending sort.

sortMultisortKey string optional
"shiftKey"

A string of the multi-column sort key.

cancelSelection boolean optional
true

Boolean flag indicating iftablesorter should cancel selection of the table headers text.

sortList Array optional

An array containing objects specifying sorting. By passing more than one object, multi-sorting will be applied. Object structure: { : <String 'asc' or 'desc'> }

Source: