Extra Block Types (EBT) - New Layout Builder experience❗

Extra Block Types (EBT) - styled, customizable block types: Slideshows, Tabs, Cards, Accordions and many others. Built-in settings for background, DOM Box, javascript plugins. Experience the future of layout building today.

Demo EBT modules Download EBT modules

❗Extra Paragraph Types (EPT) - New Paragraphs experience

Extra Paragraph Types (EPT) - analogical paragraph based set of modules.

Demo EPT modules Download EPT modules

Scroll

Drupal 8 Javascript

Drupal 8 Javascript
, by
Drupal 8 Javascript
1 answer
votes: 1372
Answer

To add jQuery once as an explicit dependency of a custom library, add core/jquery.once as shown below in MODULE.libraries.yml or THEME.libraries.yml:

foobar:
  js:
    js/foobar.js: {}
  dependencies:
    - core/jquery
    - core/jquery.once

A really basic example:

Drupal.behaviors.myBehavior = {
  attach: function (context, settings) {
    // Using once() to apply the myCustomBehaviour effect when you want to run just one function.
    $('input.myCustomBehavior', context).once('myCustomBehavior').addClass('processed');

    // Using once() with more complexity.
    $('input.myCustom', context).once('mySecondBehavior').each(function () {
      if ($(this).visible()) {
        $(this).css('background', 'green');
      }
      else {
        $(this).css('background', 'yellow').show();
      }
    });
  }
};

Drupal API documentation:

https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview

See also: