Working with JS
Much like CSS, for JS to be loaded, the script needs to be referenced by a library, and then the library needs to be loaded by the theme. The JS can be placed in any directory but is typically placed in the themename/js
directory.
Drupal behaviors
Drupal behaviors is the term for the JavaScript API that allows JS to process elements that are injected via AJAX.
It usually runs multiple times when a page is loaded. It’ll run first and pass in the document as context. The subsequent times it loads it will then pass in the AJAX element as context:
((Drupal) => { Drupal.behaviors.myBehavior = { attach(context) { context.querySelector('.my-element')?.addClass('is-processed'); }, }; })(Drupal);
In the preceding example, we create a behavior called myBehavior
. We add this to the Drupal.behaviors
array that Drupal runs whenever...