blob: 7fd01b33ca9c17a02f32f0d6ff7cae25ff0c3c1f (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
const expandedClass = "e-content--expanded";
export function toggleContentExpanded(id) {
const content = document.querySelector(`[data-content-id=${id}]`);
const button = document.querySelector(`[data-content-id=${id}] + button`);
if (!content) {
throw new Error(`No content found with ID: ${id}`);
}
const classes = content.getAttribute("class").split(" ");
const wasExpanded = classes.includes(expandedClass);
if (wasExpanded) {
const newClasses = classes.filter((c) => c != expandedClass);
content.setAttribute("class", newClasses.join(" "));
} else {
content.setAttribute("class", [...classes, expandedClass].join(" "));
}
if (!button) {
console.warn(
`Toggled content expansion, but no button next to content with ID: ${id}`,
);
} else {
if (wasExpanded) {
button.textContent = "Read more";
} else {
button.textContent = "Read less";
}
}
}
export function addExpandItemButtons() {
for (const content of document.querySelectorAll(".e-content")) {
const contentId = crypto.randomUUID();
content.setAttribute("data-content-id", contentId);
const button = document.createElement("button");
button.textContent = "Read more";
button.addEventListener("click", () => toggleContentExpanded(contentId));
content.insertAdjacentElement("afterend", button);
}
}
|