After successfully implementing the functionality for the previous and next buttons in my script, I was requested to include the date between the buttons like this:
btnPrev issueDate btnNext
< Date >
Although I tried adding the date between the PREV and NEXT buttons in the code, it doesn't show up on the page. How can I properly insert text between those two buttons?
type: "span",
textContent: "November 1, 2022",
...this.btnIssue,
});
This is the complete script:
constructor(selector, options = {}) {
Object.assign(
this, {
EL: document.querySelector(selector),
page: 0,
selector,
// btnTabs: {}, // Custom attributes for tabs (navigation) buttons
btnPrev: {}, // Custom attributes for PREV button
btnNext: {}, // Custom attributes for NEXT button
classActive: "is-active",
onChange: () => {},
},
options
);
this.EL_pages = this.EL.children;
this.EL_pagination = document.querySelectorAll(`[data-tabs-pagination="${this.selector}"]`);
this.EL_navigation = document.querySelectorAll(`[data-tabs-navigation="${this.selector}"]`);
this.total = this.EL_pages.length;
this.EL_prev = this._ELNew("button", {
type: "button",
textContent: "<",
onclick: () => this.prev(),
...this.btnPrev,
});
this.EL_issue = this._ELNew("span", {
type: "span",
textContent: "November 1, 2022",
});
this.EL_next = this._ELNew("button", {
type: "button",
textContent: ">",
onclick: () => this.next(),
...this.btnNext,
});
this.EL_buttons = Array.from(Array(this.total)).reduce((arr, _, i) => {
const EL_btn = this._ELNew("button", {
type: "button",
textContent: i + 1,
onclick: () => (this._page = i),
...this.btnPagination,
});
arr.push(EL_btn);
return arr;
}, []);
this._init();
}
// Utility function - New element
_ELNew = (sel, attr) => Object.assign(document.createElement(sel), attr || {});
// Fix negative modulo index
_mod = (n) => ((n % this.total) + this.total) % this.total;
// Initialize
_init() {
// Append nav buttons to DOM
this.EL_pagination.forEach((EL) => EL.append(...this.EL_buttons));
this.EL_navigation.forEach((EL) => EL.append(this.EL_prev, this.EL_next));
// Set current page
this._page = this.page;
}
prev(n = 1) {
this._page -= n;
return this;
}
next(n = 1) {
this._page += n;
return this;
}
show(idx) {
this._page = idx;
return this;
}
set _page(n) {
this.page = this._mod(n);
[...this.EL_pages, ...this.EL_buttons].forEach((EL) => EL.classList.remove(this.classActive));
[this.EL_pages[this.page], this.EL_buttons[this.page]].forEach((EL) => EL.classList.add(this.classActive));
// Provide a callback
this.onChange.call(this);
}
get _page() {
return this.page;
}
}
// Use like:
const mySectionTabs = new Tabs("#issue-nav", {
onChange() {
console.clear();
console.log(`Current page index: ${this.page}`);
}
});