This is what I've tried, is there a better way of doing it? if so please LMK. Thanks :).
There's a div inside my HTML with an Id of 'content'. Each button have an eventListener and when clicked the eventListener checks the button's dataset and passes it through a dictionary and whatever value they get back will be the page the display inside 'content'.
HTML:
<body>
<div ></div>
</body>
Javascript:
const content = document.querySelector(".content");
const pageOne = `This is page one of the three pages. <button id="next" onclick="showNextPage()" data-next="pageThree">Show Next Page</button> <button id="prev" data-prev="pageOne">Show Previous Page</button>`;
const pageTwo = `Behold the second page of the three pages. <button id="next" onclick="showNextPage()" data-next="pageThree"> Show Next Page</button><button id="prev" data-prev="pageOne">Show Previous Page</button>`;
const pageThree = `Finally the last page, page three of the three pages. <button id="next" onclick="showNextPage()" data-next="pageOne"> Show Next Page</button><button id="prev" data-prev="pageTwo">Show Previous Page</button>`;
content.innerHTML = pageOne;
const dict = {
"pageOne": pageOne,
"pageTwo": pageTwo,
"pageThree": pageThree,
}
function showNextPage() {
let button = document.getElementById("next");
content.innerHTML = dict[button.dataset.next];
}
function showPrevPage() {
let button = document.getElementById("prev");
content.innerHTML = dict[button.dataset.prev];
}
CodePudding user response:
You can try solving the pagination with the counter variable, and additional function for checking if the buttons should be disabled. Also rewrite object to an array of objects, for easier accessing current page's content.
When it comes to templating as you wrote, consider using also maybe Handlebars or similar.
I played a bit to help you, if needed:
const content = document.querySelector(".content");
const next = document.querySelector("#next");
const prev = document.querySelector("#prev");
let counter = 0;
const dict = [{
contentText: "This is page one of the three pages."
},
{
contentText: "Behold the second page of the three pages"
},
{
contentText: "Finally the last page, page three of the three pages."
}
]
function showNextPage() {
counter = 1;
check()
}
function showPrevPage() {
counter -= 1;
check()
}
function check() {
// sets new html content
content.innerHTML = dict[counter].contentText
// disabling buttons
if (counter == 0) {
prev.disabled = true;
} else if (counter == 2) {
next.disabled = true;
} else {
next.disabled = false;
prev.disabled = false;
}
}
<body>
<div >
This is page one of the three pages.
</div>
<button id="prev" disabled="true" onclick="showPrevPage()">Show Previous Page</button>
<button id="next" onclick="showNextPage()">Show Next Page</button>
</body>