Issue
I have a page with multiple divs. I want there to be buttons that, when clicked on, go to the next div. E.g. Div #1 is visible on the page. It has a 'next' button on it. When the user clicks the next button, it goes to another div on the same page that was previously hidden/invisible (set to display:none). This is the webpage I'm editing. I'm willing to use non-JS solutions to this if that's possible but I assume JS is the best/most efficient way to approach this?
I was thinking something like this but copying it didn't work and neither did anything else I've tried no matter how much I modified my code.
I don't know much about javascript yet so it's my fault for trying this before having the necessary knowledge but I'm desperate to make it work haha
This is a highly simplified version of what I was trying to do with my code:
CSS:
.entry {
text-align: left;
padding-top: 0px;
padding-bottom: 1px;
padding-left: 10px;
padding-right: 10px;
font-size: 15px;
font-family: Book Antiqua;
width: 550px;
height:500px;
overflow:auto;
margin: auto;
}
HTML:
<div class="entry">
<p>paragraph text 1</p>
<button class="next">Next</button>
</div>
<div class="entry" style="display:none;">
<p>paragraph text 2</p>
<button class="back">Back</button>
<button class="next">Next</button>
</div>
<div class="entry" style="display:none;">
<p>paragraph text 3</p>
<button class="back">Back</button>
<button class="next">Next</button>
</div>
Javascript:
$('.next').click(function(){
$(this).parent().hide().next().show();//hide parent and show next
});
$('.back').click(function(){
$(this).parent().hide().prev().show();//hide parent and show previous
});
I believe the problem is to do with a lack of a parent element? But I'm not sure.
Solution
Plain JS solution, so it doesn't require the use of the jQuery library. more lightweight and efficient.
var entries = document.querySelectorAll(".entry");
var nextButtons = document.querySelectorAll(".next");
var backButtons = document.querySelectorAll(".back");
nextButtons.forEach(function(button, index) {
button.addEventListener("click", function() {
entries[index].style.display = "none";
entries[index + 1].style.display = "block";
});
});
backButtons.forEach(function(button, index) {
button.addEventListener("click", function() {
entries[index + 1].style.display = "none";
entries[index].style.display = "block";
});
});
Answered By - Afzal K.
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.