Namespace: Drupal

Drupal

Global Drupal object.

All Drupal JavaScript APIs are contained in this namespace.

Source:

Classes

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

Namespaces

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

Members

(static) MediaLibrary

Wrapper object for the current state of the media library.

Source:

(static) tabbingManager :Drupal~TabbingManager

Type:
Source:

(static) user :object

An object containing CSS classes used for password widget.

Type:
  • object
Properties:
Name Type Description
passwordParent string

A CSS class for the parent element.

passwordsMatch string

A CSS class indicating password match.

passwordsNotMatch string

A CSS class indicating passwords doesn't match.

passwordWeak string

A CSS class indicating weak password strength.

passwordFair string

A CSS class indicating fair password strength.

passwordGood string

A CSS class indicating good password strength.

passwordStrong string

A CSS class indicating strong password strength.

widgetInitial string

Initial CSS class that should be removed on a state change.

passwordEmpty string

A CSS class indicating password has not been filled.

passwordFilled string

A CSS class indicating password has been filled.

confirmEmpty string

A CSS class indicating password confirmation has not been filled.

confirmFilled string

A CSS class indicating password confirmation has been filled.

Source:

Methods

(static) 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.

Parameters:
Name Type Description
settings object

The settings object passed to Drupal.Ajax constructor.

Properties
Name Type Attributes 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.

Source:
See:
Returns:

The created Ajax object.

Type
Drupal.Ajax
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();
  }
};

(static) announce(text, priorityopt) → {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.

Parameters:
Name Type Attributes Default Description
text string

A string to be read by the UA.

priority string <optional>
'polite'

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

Source:
See:
Returns:

The return of the call to debounce.

Type
function

(static) attachBehaviors(contextopt, settingsopt)

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.)

Parameters:
Name Type Attributes Default Description
context HTMLDocument | HTMLElement <optional>
document

An element to attach behaviors to.

settings object <optional>
drupalSettings

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

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

(static) checkPlain(str) → {string}

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

Parameters:
Name Type Description
str string

The string to be encoded.

Source:
Returns:

The encoded string.

Type
string

(static) 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.

Parameters:
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.

Source:
Returns:

The debounced function.

Type
function

(static) deprecatedProperty(deprecation) → {Object}

Triggers deprecation error when object property is being used.

Parameters:
Name Type Description
deprecation Object

The deprecation options.

Properties
Name Type Description
target Object

The targeted object.

deprecatedProperty string

A key of the deprecated property.

message string

The deprecation message.

Source:
See:
Returns:
Type
Object

(static) deprecationError(deprecation)

Triggers deprecation error.

Deprecation errors are only triggered if deprecation errors haven't been suppressed.

Parameters:
Name Type Description
deprecation Object

The deprecation options.

Properties
Name Type Description
message string

The deprecation message.

Source:
See:

(static) detachBehaviors(contextopt, settingsopt, triggeropt)

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.

Parameters:
Name Type Attributes Default Description
context HTMLDocument | HTMLElement <optional>
document

An element to detach behaviors from.

settings object <optional>
drupalSettings

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

trigger string <optional>
'unload'

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.
Source:
See:
Throws:
Drupal~DrupalBehaviorError

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

Polyfill HTML5 dialog element with jQueryUI.

Parameters:
Name Type Description
element HTMLElement

The element that holds the dialog.

options object

jQuery UI options to be passed to the dialog.

Source:
Returns:

The dialog instance.

Type
Drupal.dialog~dialogDefinition

(static) displace(broadcastopt) → {Drupal~displaceOffset}

Informs listeners of the current offset dimensions.

Parameters:
Name Type Attributes 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
Source:
Fires:
Returns:

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.

Type
Drupal~displaceOffset

(static) editorAttach(field, format)

Attaches editor behaviors to the field.

Parameters:
Name Type Description
field HTMLElement

The textarea DOM element.

format object

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

Source:
Fires:
Listens to Events:
  • event:change

(static) editorDetach(field, format, trigger)

Detaches editor behaviors from the field.

Parameters:
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.

Source:

(static) encodePath(item) → {string}

Encodes a Drupal path for use in a URL.

For aesthetic reasons slashes are not escaped.

Parameters:
Name Type Description
item string

Unencoded path.

Source:
Returns:

The encoded path.

Type
string

(static) evaluatePasswordStrength(password, passwordSettings) → {object}

Evaluate the strength of a user's password.

Returns the estimated strength and the relevant output message.

Parameters:
Name Type Description
password string

The password to evaluate.

passwordSettings object

A password settings object containing the text to display and the CSS classes for each strength level.

Source:
Returns:

An object containing strength, message, indicatorText and indicatorClass.

Type
object

(static) 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.
Source:
See:
Returns:

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}
  }
}
Type
object
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: [] }
  }
}

(static) formatPlural(count, singular, plural, argsopt, optionsopt) → {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.

Parameters:
Name Type Attributes 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.

Source:
Returns:

A translated string.

Type
string

(static) formatString(str, args) → {string}

Replaces placeholders with sanitized values in a string.

Parameters:
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:

Source:
See:
Returns:

The formatted string.

Type
string

(static) layoutBuilderBlockUpdate(item, from, to)

Callback used in Drupal.behaviors.layoutBuilderBlockDrag.

Parameters:
Name Type Description
item HTMLElement

The HTML element representing the repositioned block.

from HTMLElement

The HTML element representing the previous parent of item

to HTMLElement

The HTML element representing the current parent of item

Source:
See:

(static) menuUiUpdateParentList()

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

Source:

(static) 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.

Parameters:
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.

Source:
Returns:

The replaced string.

Type
string

(static) t(str, argsopt, optionsopt) → {string}

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

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

Parameters:
Name Type Attributes 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.

Properties
Name Type Attributes Default Description
context string <optional>
''

The context the source string belongs to.

Source:
Returns:

The formatted string. The translated string.

Type
string

(static) tableSelect()

Callback used in Drupal.behaviors.tableSelect.

Source:

(static) tableSelectRange(from, to, state)

Parameters:
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.

Source:

(static) 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.

Parameters:
Name Type Description
error Error | string

The error to be thrown.

Source:

(static) url(path) → {string}

Returns the URL to a Drupal page.

Parameters:
Name Type Description
path string

Drupal path to transform to URL.

Source:
Returns:

The full URL.

Type
string

Type Definitions

behavior

Type:
  • object
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.

Source:

behaviorAttach(context, settingsnullable)

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

Parameters:
Name Type Attributes 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.

Source:
See:

behaviorDetach(context, settings, trigger)

Reverts and cleans up JavaScript behavior initialization.

Parameters:
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'.

Source:
See:

displaceOffset

Type:
  • object
Properties:
Name Type Description
top number
left number
right number
bottom number
Source: