Namespace: Drupal

Drupal

Global Drupal object.

All Drupal JavaScript APIs are contained in this namespace.

Classes

Ajax
AjaxCommands
AjaxError
CollapsibleDetails
DropButton
EditorFeature
EditorFeatureHTMLRule
FilterStatus
ProgressBar
tableDrag
TableHeader
TableResponsive
verticalTab
TabbingContext
TabbingManager

Namespaces

autocomplete
behaviors
ckeditor
color
contextual
contextualToolbar
editorConfiguration
editors
fieldUIDisplayOverview
fieldUIOverview
file
filterConfiguration
history
quickedit
states
theme
toolbar
tour
views
Views
viewsUi

Members

staticDrupal.tabbingManagerDrupal~TabbingManager

Methods

staticDrupal.ajax(settings){Drupal.Ajax}

Provides Ajax page updating via jQuery $.ajax.

This function is designed to improve developer experience by wrapping the initialization of Drupal.Ajax objects and storing all created objects in the Drupal.ajax.instances array.

Name Type Description
settings object

The settings object passed to Drupal.Ajax constructor.

Name Type Description
base string optional

Base is passed to Drupal.Ajax constructor as the 'base' parameter.

element HTMLElement optional

Element parameter of Drupal.Ajax constructor, element on which event listeners will be bound.

See:
Returns:
Type Description
Drupal.Ajax The created Ajax object.
Example
Drupal.behaviors.myCustomAJAXStuff = {
  attach: function (context, settings) {

    var ajaxSettings = {
      url: 'my/url/path',
      // If the old version of Drupal.ajax() needs to be used those
      // properties can be added
      base: 'myBase',
      element: $(context).find('.someElement')
    };

    var myAjaxObject = Drupal.ajax(ajaxSettings);

    // Declare a new Ajax command specifically for this Ajax object.
    myAjaxObject.commands.insert = function (ajax, response, status) {
      $('#my-wrapper').append(response.data);
      alert('New content was appended to #my-wrapper');
    };

    // This command will remove this Ajax object from the page.
    myAjaxObject.commands.destroyObject = function (ajax, response, status) {
      Drupal.ajax.instances[this.instanceIndex] = null;
    };

    // Programmatically trigger the Ajax request.
    myAjaxObject.execute();
  }
};

staticDrupal.announce(text, priority){function}

Triggers audio UAs to read the supplied text.

The aria-live region will only read the text that currently populates its text node. Replacing text quickly in rapid calls to announce results in only the text from the most recent call to Drupal.announce being read. By wrapping the call to announce in a debounce function, we allow for time for multiple calls to Drupal.announce to queue up their messages. These messages are then joined and append to the aria-live region as one text node.

Name Type Default Description
text string

A string to be read by the UA.

priority string 'polite' optional

A string to indicate the priority of the message. Can be either 'polite' or 'assertive'.

See:
Returns:
Type Description
function The return of the call to debounce.

staticDrupal.attachBehaviors(context, settings)

Defines a behavior to be run during attach and detach phases.

Attaches all registered behaviors to a page element.

Behaviors are event-triggered actions that attach to page elements, enhancing default non-JavaScript UIs. Behaviors are registered in the Drupal.behaviors object using the method 'attach' and optionally also 'detach'.

Drupal.attachBehaviors is added below to the jQuery.ready event and therefore runs on initial page load. Developers implementing Ajax in their solutions should also call this function after new page content has been loaded, feeding in an element to be processed, in order to attach all behaviors to the new content.

Behaviors should use var elements = $(context).find(selector).once('behavior-name'); to ensure the behavior is attached only once to a given element. (Doing so enables the reprocessing of given elements, which may be needed on occasion despite the ability to limit behavior attachment to a particular element.)

Name Type Default Description
context HTMLDocument | HTMLElement document optional

An element to attach behaviors to.

settings object drupalSettings optional

An object containing settings for the current context. If none is given, the global drupalSettings object is used.

See:
Throws:
Drupal~DrupalBehaviorError
Example
Drupal.behaviors.behaviorName = {
  attach: function (context, settings) {
    // ...
  },
  detach: function (context, settings, trigger) {
    // ...
  }
};

staticDrupal.checkPlain(str){string}

Encodes special characters in a plain-text string for display as HTML.

Name Type Description
str string

The string to be encoded.

Returns:
Type Description
string The encoded string.

staticDrupal.debounce(func, wait, immediate){function}

Limits the invocations of a function in a given time frame.

The debounce function wrapper should be used sparingly. One clear use case is limiting the invocation of a callback attached to the window resize event.

Before using the debounce function wrapper, consider first whether the callback could be attached to an event that fires less frequently or if the function can be written in such a way that it is only invoked under specific conditions.

Name Type Description
func function

The function to be invoked.

wait number

The time period within which the callback function should only be invoked once. For example if the wait period is 250ms, then the callback will only be called at most 4 times per second.

immediate bool

Whether we wait at the beginning or end to execute the function.

Returns:
Type Description
function The debounced function.

staticDrupal.detachBehaviors(context, settings, trigger)

Detaches registered behaviors from a page element.

Developers implementing Ajax in their solutions should call this function before page content is about to be removed, feeding in an element to be processed, in order to allow special behaviors to detach from the content.

Such implementations should use .findOnce() and .removeOnce() to find elements with their corresponding Drupal.behaviors.behaviorName.attach implementation, i.e. .removeOnce('behaviorName'), to ensure the behavior is detached only from previously processed elements.

Name Type Default Description
context HTMLDocument | HTMLElement document optional

An element to detach behaviors from.

settings object drupalSettings optional

An object containing settings for the current context. If none given, the global drupalSettings object is used.

trigger string 'unload' optional

A string containing what's causing the behaviors to be detached. The possible triggers are:

  • 'unload': The context element is being removed from the DOM.
  • 'move': The element is about to be moved within the DOM (for example, during a tabledrag row swap). After the move is completed, Drupal.attachBehaviors is called, so that the behavior can undo whatever it did in response to the move. Many behaviors won't need to do anything simply in response to the element being moved, but because IFRAME elements reload their "src" when being moved within the DOM, behaviors bound to IFRAME elements (like WYSIWYG editors) may need to take some action.
  • 'serialize': When an Ajax form is submitted, this is called with the form as the context. This provides every behavior within the form an opportunity to ensure that the field elements have correct content in them before the form is serialized. The canonical use-case is so that WYSIWYG editors can update the hidden textarea to which they are bound.
See:
Throws:
Drupal~DrupalBehaviorError

staticDrupal.dialog(element, options){Drupal.dialog~dialogDefinition}

Polyfill HTML5 dialog element with jQueryUI.

Name Type Description
element HTMLElement

The element that holds the dialog.

options object

jQuery UI options to be passed to the dialog.

Returns:
Type Description
Drupal.dialog~dialogDefinition The dialog instance.

staticDrupal.displace(broadcast){Drupal~displaceOffset}

Informs listeners of the current offset dimensions.

Name Type Description
broadcast bool optional

When true or undefined, causes the recalculated offsets values to be broadcast to listeners.

Properties:
Name Type Description
offsets Drupal~displaceOffset
Fires:
Returns:
Type Description
Drupal~displaceOffset An object whose keys are the for sides an element -- top, right, bottom and left. The value of each key is the viewport displacement distance for that edge.

staticDrupal.editorAttach(field, format)

Attaches editor behaviors to the field.

Name Type Description
field HTMLElement

The textarea DOM element.

format object

The text format that's being activated, from drupalSettings.editor.formats.

Fires:
Listens to Events:
  • event:change

staticDrupal.editorDetach(field, format, trigger)

Detaches editor behaviors from the field.

Name Type Description
field HTMLElement

The textarea DOM element.

format object

The text format that's being activated, from drupalSettings.editor.formats.

trigger string

Trigger value from the detach behavior.

staticDrupal.encodePath(item){string}

Encodes a Drupal path for use in a URL.

For aesthetic reasons slashes are not escaped.

Name Type Description
item string

Unencoded path.

Returns:
Type Description
string The encoded path.

staticDrupal.evaluatePasswordStrength(password, translate){object}

Evaluate the strength of a user's password.

Returns the estimated strength and the relevant output message.

Name Type Description
password string

The password to evaluate.

translate object

An object containing the text to display for each strength level.

Returns:
Type Description
object An object containing strength, message, indicatorText and indicatorClass.

staticDrupal.FilterHTMLRule(){object}

A text filter HTML rule object.

Intended to be used in combination with Drupal.FilterStatus.

A text filter rule object describes:

  1. allowed or forbidden tags: (optional) whitelist or blacklist HTML tags
  2. restricted tag properties: (optional) whitelist or blacklist attributes, styles and classes on a set of HTML tags.

Typically, each text filter rule object does either 1 or 2, not both.

The structure can be very clearly seen below:

  1. use the "tags" key to list HTML tags, and set the "allow" key to either true (to allow these HTML tags) or false (to forbid these HTML tags). If you leave the "tags" key's default value (the empty array), no restrictions are applied.
  2. all nested within the "restrictedTags" key: use the "tags" subkey to list HTML tags to which you want to apply property restrictions, then use the "allowed" subkey to whitelist specific property values, and similarly use the "forbidden" subkey to blacklist specific property values.
See:
Returns:
Type Description
object An object with the following structure:
{
  tags: Array,
  allow: null,
  restrictedTags: {
    tags: Array,
    allowed: {attributes: Array, styles: Array, classes: Array},
    forbidden: {attributes: Array, styles: Array, classes: Array}
  }
}
Examples

Whitelist the "p", "strong" and "a" HTML tags.

{
  tags: ['p', 'strong', 'a'],
  allow: true,
  restrictedTags: {
    tags: [],
    allowed: { attributes: [], styles: [], classes: [] },
    forbidden: { attributes: [], styles: [], classes: [] }
  }
}

For the "a" HTML tag, only allow the "href" attribute and the "external" class and disallow the "target" attribute.

{
  tags: [],
  allow: null,
  restrictedTags: {
    tags: ['a'],
    allowed: { attributes: ['href'], styles: [], classes: ['external'] },
    forbidden: { attributes: ['target'], styles: [], classes: [] }
  }
}

For all tags, allow the "data-*" attribute (that is, any attribute that begins with "data-").

{
  tags: [],
  allow: null,
  restrictedTags: {
    tags: ['*'],
    allowed: { attributes: ['data-*'], styles: [], classes: [] },
    forbidden: { attributes: [], styles: [], classes: [] }
  }
}

staticDrupal.formatPlural(count, singular, plural, args, options){string}

Formats a string containing a count of items.

This function ensures that the string is pluralized correctly. Since Drupal.t is called by this function, make sure not to pass already-localized strings to it.

See the documentation of the server-side \Drupal\Core\StringTranslation\TranslationInterface::formatPlural() function for more details.

Name Type Description
count number

The item count to display.

singular string

The string for the singular case. Please make sure it is clear this is singular, to ease translation (e.g. use "1 new comment" instead of "1 new"). Do not use @count in the singular string.

plural string

The string for the plural case. Please make sure it is clear this is plural, to ease translation. Use @count in place of the item count, as in "@count new comments".

args object optional

An object of replacements pairs to make after translation. Incidences of any key in this array are replaced with the corresponding value. See Drupal.formatString. Note that you do not need to include @count in this array. This replacement is done automatically for the plural case.

options object optional

The options to pass to the Drupal.t function.

Returns:
Type Description
string A translated string.

staticDrupal.formatString(str, args){string}

Replaces placeholders with sanitized values in a string.

Name Type Description
str string

A string with placeholders.

args object

An object of replacements pairs to make. Incidences of any key in this array are replaced with the corresponding value. Based on the first character of the key, the value is escaped and/or themed:

See:
Returns:
Type Description
string The formatted string.

staticDrupal.menuUiUpdateParentList()

Function to set the options of the menu parent item dropdown.

staticDrupal.stringReplace(str, args, keys){string}

Replaces substring.

The longest keys will be tried first. Once a substring has been replaced, its new value will not be searched again.

Name Type Description
str string

A string with placeholders.

args object

Key-value pairs.

keys Array | null

Array of keys from args. Internal use only.

Returns:
Type Description
string The replaced string.

staticDrupal.t(str, args, options){string}

Translates strings to the page language, or a given language.

See the documentation of the server-side t() function for further details.

Name Type Description
str string

A string containing the English text to translate.

args Object.<string, string> optional

An object of replacements pairs to make after translation. Incidences of any key in this array are replaced with the corresponding value. See Drupal.formatString.

options object optional

Additional options for translation.

Name Type Default Description
context string '' optional

The context the source string belongs to.

Returns:
Type Description
string The formatted string. The translated string.

staticDrupal.tableSelect()

Callback used in Drupal.behaviors.tableSelect.

staticDrupal.tableSelectRange(from, to, state)

Name Type Description
from HTMLElement

The HTML element representing the "from" part of the range.

to HTMLElement

The HTML element representing the "to" part of the range.

state bool

The state to set on the range.

staticDrupal.throwError(error)

Helper to rethrow errors asynchronously.

This way Errors bubbles up outside of the original callstack, making it easier to debug errors in the browser.

Name Type Description
error Error | string

The error to be thrown.

staticDrupal.url(path){string}

Returns the URL to a Drupal page.

Name Type Description
path string

Drupal path to transform to URL.

Returns:
Type Description
string The full URL.

Type Definitions

behaviorobject

Properties:
Name Type Description
attach Drupal~behaviorAttach

Function run on page load and after an Ajax call.

detach Drupal~behaviorDetach

Function run when content is serialized or removed from the page.

behaviorAttach(context, settings)

Custom error thrown after attach/detach if one or more behaviors failed. Initializes the JavaScript behaviors for page loads and Ajax requests.

Name Type Description
context HTMLDocument | HTMLElement

An element to detach behaviors from.

settings object nullable

An object containing settings for the current context. It is rarely used.

See:

behaviorDetach(context, settings, trigger)

Reverts and cleans up JavaScript behavior initialization.

Name Type Description
context HTMLDocument | HTMLElement

An element to attach behaviors to.

settings object

An object containing settings for the current context.

trigger string

One of 'unload', 'move', or 'serialize'.

See:

displaceOffsetobject

Properties:
Name Type Description
top number
left number
right number
bottom number