Answer the question
In order to leave comments, you need to log in
Give an example of the most economical code?
The task is very simple, by clicking on the next button, we display the contents of the next section tag, back - of the previous one.
<section>
<h1>1</h1>
<button>Next</button>
</section>
<section>
<h1>2</h1>
<button>Back</button>
<button>Next</button>
</section>
<section>
<h1>3</h1>
<button>Back</button>
<button>Next</button>
</section>
<section>
<h1>4</h1>
<button>Back</button>
</section>
Answer the question
In order to leave comments, you need to log in
On jQuery:
https://codepen.io/tsymbal_su/pen/PoPKXGK
css:
section.active {
display: block;
}
section:not(.active) {
display: none;
}
jQuery(document).ready(function($){
$("section:nth-child(1)").addClass("active");
$(document).on("click","section.active button",function(){
if ($(this).text()=="Next") {
$(this).parents("section").removeClass("active").next("section").addClass("active");
} else if ($(this).text()=="Back") {
$(this).parents("section").removeClass("active").prev("section").addClass("active");
}
});
})
No jquery
https://jsfiddle.net/melchiorio/6sqoherp/
6 lines of js and one wrapper tag
Without changing html
section{
display: none;
}
.block{
display: block;
}
let m = document.getElementsByTagName('section');
let i = 0;
let y = 0;
loop(i);
function loop(i){
m[y].classList.remove('block');
m[i].classList.add('block');
let buttons = m[i].getElementsByTagName('button');
if (buttons.length > 1) {
if (buttons[0].innerHTML == 'Back') {
buttons[0].onclick = function () {
console.log('back');
y = i;
i--;
loop(i);
}
}
if (buttons[1].innerHTML == 'Next') {
buttons[1].onclick = function () {
console.log('next');
y = i;
i++;
loop(i);
}
}
}else{
if (buttons[0].innerHTML == 'Next') {
buttons[0].onclick = function () {
console.log('next');
y = i;
i++;
loop(i);
}
}
if (buttons[0].innerHTML == 'Back') {
buttons[0].onclick = function () {
console.log('back');
y = i;
i--;
loop(i);
}
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question