Fernando Souza
Fernando Souza

Reputation: 1779

Navigate an array of functions by click

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 ();

Upvotes: 0

Views: 52

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038830

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.

Upvotes: 1

Related Questions