'changing div content using button
I want to make a button that will create a back page if I click this it will return to the last div content. I already have the function for the next page but I'm already ran out of logic for making a function for the back page button.
Here is my code for the content and my function for the next()
function next() {
if ($('#content1').hasClass('')) {
$('#content2').removeClass('hidden');
$('#back').removeClass('hidden');
$('#content1').addClass('hidden');
} else if ($('#content2').hasClass('')) {
$('#content2').addClass('hidden');
$('#content3').removeClass('hidden');
} else if ($('#content3').hasClass('')) {
$('#content3').addClass('hidden');
$('#content4').removeClass('hidden');
} else if ($('#content4').hasClass('')) {
$('#content4').addClass('hidden');
$('#content5').removeClass('hidden');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="myDiv">
<div id="content1">
<h1>1</h1>
</div>
<div id="content2" class="hidden">
<h1>2</h1>
</div>
<div id="content3" class="hidden">
<h1>3</h1>
</div>
<div id="content4" class="hidden">
<h1>4</h1>
</div>
<div id="content5" class="hidden">
<h1>5</h1>
</div>
<button onclick='next()'>Next Page</button>
<button id="back" onclick='back()' class="hidden">Back Page</button>
</div>
Solution 1:[1]
You can simplify this.
Here I remove the inline functions and have only one function.
Also no need for classes.
$(function() {
const $container = $("div.myDiv");
const $contents = $(".myDiv > div");
const last = $contents.length - 1;
$(".nav").on("click", function() {
const isNext = $(this).is("#next"); // we clicked next
const $cur = $container.find("div:visible"); // currently visible
const $show = isNext ? $cur.next() : $cur.prev(); // next or prev div?
const idx = $show.index();
$("#prev").toggle(idx >= 1);
$("#next").toggle(idx < last);
$("#reveal").toggle(idx >= last);
$cur.hide();
$show.show();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div class="myDiv">
<div id="content1">
<h1>1</h1>
</div>
<div id="content2" hidden>
<h1>2</h1>
</div>
<div id="content3" hidden>
<h1>3</h1>
</div>
<div id="content4" hidden>
<h1>4</h1>
</div>
<div id="content5" hidden>
<h1>5</h1>
</div>
<button class="nav" id="prev" hidden>Previous Page</button>
<button class="nav" id="next">Next Page</button>
<button id="reveal" hidden>Reveal</button>
</div>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
