Reputation: 1
I am using plain JavaScript and JQuery in my program. I have a start button that just lets the program run freely.
<button class="button is-link" id= "start"> Start </button>
document.getElementsByTagName('button')[0].addEventListener('click', function() {
step1();
step2();
step3();
step4();
step5();
})
function step1() {
some action
}
function step2() {
some action
}
function step3() {
some action
}
function step4() {
some action
}
function step5() {
some action
}
How would I also include a next and previous button where I can show each function separately and go back and forth between them?
Upvotes: 0
Views: 679
Reputation: 904
Simple switch case will be helpful.
<div id="text">Click start to run the app!</div>
<button class="button is-link" id= "start" onclick="start()"> Start </button>
<button class="button is-link" id= "next" onclick="next()"> Next </button>
<button class="button is-link" id= "previous" onclick="previous()"> Previous </button>
<script>
var step = 0;
function start() {
step = 1;
handleStep();
}
function next() {
step++;
handleStep();
}
function previous() {
if (step > 0)
step--;
handleStep();
}
function handleStep() {
switch (step) {
case 1:
step1();
break;
case 2:
step2();
break;
case 3:
step3();
break;
case 4:
step4();
break;
case 5:
step5();
break;
default:
step1();
// Go to the first step or any other logic as you want
break;
}
}
function setText(text) {
document.getElementById("text").innerHTML = text;
}
function step1() {
setText("Step 1");
}
function step2() {
setText("Step 2");
}
function step3() {
setText("Step 3");
}
function step4() {
setText("Step 4");
}
function step5() {
setText("Step 5");
}
</script>
Upvotes: 1
Reputation:
First of all, there isn't any jQuery in your code (keep it that way) :)
Secondly, if the page isn't reloading, then you should attach a single event listener like:
var step = 0;
ele.addEventListener(function() {
// basically store which step you're on and the click adjusts the step
// and then calls the function associated with that step
step++;
doNextStep(step);
});
Upvotes: 1