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();
}
});
}
};
To add jQuery once as an explicit dependency of a custom library, add
core/jquery.onceas shown below in MODULE.libraries.yml or THEME.libraries.yml:A really basic example:
Drupal API documentation:
https://www.drupal.org/docs/8/api/javascript-api/javascript-api-overview
See also: