class TextExpander {
constructor(options) {
this.container = document.querySelector(options.selector);
if (!this.container) {
console.error(`Element with selector ${options.selector} not found.`);
return;
}
this.collapsedNumWords = options.collapsedNumWords || 10;
this.expandButtonText = options.expandButtonText || "Show more";
this.collapseButtonText = options.collapseButtonText || "Show less";
this.buttonColor = options.buttonColor || "#1f09cd";
this.expanded = options.expanded || false;
this.text = options.text;
this.init();
}
init() {
if (!this.container) return;
const displayText = this.expanded
? this.text
: this.text.split(" ").slice(0, this.collapsedNumWords).join(" ") + "...";
const textSpan = document.createElement("span");
textSpan.textContent = displayText;
const button = document.createElement("button");
button.textContent = this.expanded
? this.collapseButtonText
: this.expandButtonText;
button.style.background = "none";
button.style.border = "none";
button.style.font = "inherit";
button.style.cursor = "pointer";
button.style.color = this.buttonColor;
button.style.display = "inline";
button.style.padding = "0";
button.style.margin = "0";
button.addEventListener("click", () => {
this.expanded = !this.expanded;
this.init();
});
this.container.innerHTML = "";
this.container.appendChild(textSpan);
this.container.appendChild(button);
}
}
new TextExpander({
selector: "#text-expander-1",
text: "Space travel is the ultimate adventure! Imagine soaring past the stars and exploring new worlds. It's the stuff of dreams and science fiction, but believe it or not, space travel is a real thing. Humans and robots are constantly venturing out into the cosmos to uncover its secrets and push the boundaries of what's possible.",
});
new TextExpander({
selector: "#text-expander-2",
text: "Space travel requires some seriously amazing technology and collaboration between countries, private companies, and international space organizations. And while it's not always easy (or cheap), the results are out of this world. Think about the first time humans stepped foot on the moon or when rovers were sent to roam around on Mars.",
collapsedNumWords: 20,
expandButtonText: "Show text",
collapseButtonText: "Collapse text",
buttonColor: "#ff6622",
});
new TextExpander({
selector: "#text-expander-3",
text: "Space missions have given us incredible insights into our universe and have inspired future generations to keep reaching for the stars. Space travel is a pretty cool thing to think about. Who knows what we'll discover next!",
expanded: true,
});