0

I have two buttons (next and back), and I want to execute the next function of an array every time "next" is clicked, and perform the last, when "back" is clicked with jquery. I don`t know where to start...

function1 ();
function2 ();
function3 ();
function4 ();
2
  • What should happen if next is clicked and the last executed function was 4? Start all over? Commented May 8, 2016 at 13:57
  • Yes! It will start all over. Commented May 8, 2016 at 13:59

1 Answer 1

1

You could put those functions into an array:

var functions = [ function1, function2, function3, function4 ];

and have an integer to keep track of the last executed function:

var index = 0;

Now when next is clicked you would invoke the function at the specified index in the array and increment it:

functions[Math.abs(index % functions.length)]();
index++;

When back is clicked do the same but decrement the index:

functions[Math.abs(index % functions.length)]();
index--;

The index % functions.length ensures that the returned value is always within the 0-3 range which is actually the allowed index range for your array.

Sign up to request clarification or add additional context in comments.

3 Comments

If I don`t want to start it over, how is it look like?
What do you want to happen if not start over?
Just go to the last function with "next", and the "back" will comeback one function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.