Scroll
Drupal 8 Javascript
Drupal 8 Javascript
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:
- Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 theme including defining libraries and inline Javascript.
- Adding stylesheets (CSS) and JavaScript (JS) to a Drupal 8 module. Includes Attaching to a render array, Attaching a library in a twig template, Attaching configurable JavaScript via new drupalSettings
- Looking at Drupal 8's Javascript changes by Aten Design. Includes hook_library_info, Backbone and Underscore info.
- Drupal 8 change: drupal_add_css(), drupal_add_js() and drupal_add_library() removed in favor of #attached
- JS Coding standards
- Drupal 8 change: hook_library_info() is replaced by *.libraries.yml file
- Also: Placeholder for style rules that do not fit in #1778828.
- JavaScript and Drupal 8 RESTful Web Services