You need to start with:
((Drupal) => {
Drupal.behaviors.nameOfLibrary = {
attach(context) {Then it ends with:
},
};
})(Drupal);And your custom code goes in the middle. Here's an example:
((Drupal) => {
Drupal.behaviors.railToggle = {
attach(context) {
context
.querySelectorAll(".rail .component .rail-toggle")
.forEach((element) => {
let selector = element.getAttribute("aria-controls");
let parent = element.parentElement;
let target = element.parentElement.querySelector(`.${selector}`);
target.setAttribute("aria-hidden", "true");
parent.setAttribute("aria-expanded", "false");
element.addEventListener("click", (event) => {
event.preventDefault();
target.setAttribute(
"aria-hidden",
target.getAttribute("aria-hidden") === "true" ? "false" : "true"
);
parent.setAttribute(
"aria-expanded",
parent.getAttribute("aria-expanded") === "false"
? "true"
: "false"
);
});
});
},
};
})(Drupal);