So I got this class to truncate text but it's fixed, I want to to make more dynamic. I want to pass the length of text I want to truncate and make it work with multiple elements. I'm a newbie in JS classes so it's a but confusing for me right now. thank you in advance.
class readMore {
constructor() {
const end = 300;
this.content = '.readmore__content';
this.buttonToggle = '.readmore__toggle';
}
initiate() {
this.setNodes();
this.init();
this.addEventListeners();
}
setNodes() {
this.nodes = {
contentToggle: document.querySelector(this.content),
};
this.buttonToggle = this.nodes.contentToggle.parentElement.querySelector(this.buttonToggle);
}
init() {
const { contentToggle } = this.nodes;
this.stateContent = contentToggle.innerHTML;
contentToggle.innerHTML = `${this.stateContent.substring(200, `${end}`)}...`;
}
addEventListeners() {
this.buttonToggle.addEventListener('click', this.onClick.bind(this));
}
onClick(event) {
const targetEvent = event.currentTarget;
const { contentToggle } = this.nodes;
if (targetEvent.getAttribute('aria-checked') === 'true') {
targetEvent.setAttribute('aria-checked', 'false');
contentToggle.innerHTML = this.stateContent;
this.buttonToggle.innerHTML = 'Show less';
} else {
targetEvent.setAttribute('aria-checked', 'true');
contentToggle.innerHTML = `${this.stateContent.substring(200, `${end}`)}...`;
this.buttonToggle.innerHTML = 'Show more';
}
}
}
const initReadMore = new readMore();
initReadMore.initiate();