Reputation: 88
I'm trying to make a 'Next/Previous' system within a page - where it shows one specific item, or 'page', at a time. I can't seem to find a practical solution online. It's currently working, but the code is unprofessional and needlessly long/complicated especially when I want it to have up to 5 pages.
I'm not an experienced JS programmer so please go easy on me!
HTML -
<div id="page1">Page 1 <button onclick="secondPage()">Next</button></div>
<div id="page2">Page 2 <button onclick="thirdPage()">Next</button></div>
<div id="page3">Page 3 <button onclick="fourthPage()">Next</button></div>
<div id="page4">Page 4</div>
CSS -
.hidden {
display:none;
}
JS -
function secondPage() {
document.getElementById("page1").classList.add('hidden');
document.getElementById("page2").classList.remove('hidden');
document.getElementById("page3").classList.add('hidden');
document.getElementById("page4").classList.add('hidden');
}
function thirdPage() {
document.getElementById("page1").classList.add('hidden');
document.getElementById("page2").classList.add('hidden');
document.getElementById("page3").classList.remove('hidden');
document.getElementById("page4").classList.add('hidden');
}
function fourthPage() {
document.getElementById("page1").classList.add('hidden');
document.getElementById("page2").classList.add('hidden');
document.getElementById("page3").classList.add('hidden');
document.getElementById("page4").classList.remove('hidden');
}
If anyone is able to help me simplify this bit of code with a cleaner and better script that would be much appreciated. Thanks
Upvotes: 0
Views: 670
Reputation: 21672
The most basic implementation would likely be to store a global variable that keeps track of which page number is currently visible.
Using that number you could fetch the Ids dynamically, e.g. `page${currentPageNumber}`
would result in something like page2
.
Similarly, you could get the next page by doing `page${currentPageNumber+1}`
.
let currentPageNumber = 1;
function nextPage() {
document.getElementById(`page${currentPageNumber}`).classList.add("hidden"); //Hide the current page
document.getElementById(`page${currentPageNumber+1}`).classList.remove("hidden"); //Show the next page
currentPageNumber++; //Increase currentPage accordingly
}
.hidden {
display: none;
}
<div id="page1">Page 1 <button onclick="nextPage()">Next</button></div>
<div id="page2" class="hidden">Page 2 <button onclick="nextPage()">Next</button></div>
<div id="page3" class="hidden">Page 3 <button onclick="nextPage()">Next</button></div>
<div id="page4" class="hidden">Page 4</div>
Upvotes: 1