This allows automatic wrapping back to the first element without having to check that the index is past the end of the array.
Is there a similar algorithm for going to the previous item (again without having to check array limits with conditional statements)? Just changing mCurrentIndex + 1 to mCurrentIndex - 1 clearly won’t handle the case where you’re already at the first element.
@xeonproc, yes that works – but it’s using a conditional (the ternary operator) – I just thought it was cool that the next algorithm could be done with no conditional at all and was wondering if anyone had worked out something similar for a previous algorithm.
We may want to consider what we want to happen when i is bigger than (or equal to) arr.length as well.
function nextItem() {
i = i + 1; // increase i by one
i = i % arr.length; // if we’ve gone too high, start from 0 again
return arr[i]; // give us back the item of where we are now
}
Next, lets do the reverse, this time we might want to consider what should happen for negative i
function prevItem() {
if (i === 0) { // i would become 0
i = arr.length; // so put it at the other end of the array
}
i = i - 1; // decrease by one
return arr[i]; // give us back the item of where we are now
}
So far,
nextItem(); // “bar” (i === 1)
prevItem(); // “foo” (i === 0 as we did 0 + 1 - 1)
// also
prevItem(); // “baz” (decreased on 0)
nextItem(); // “foo” (increased at end of arr)
Great, so we’ve got the basic algorithms down.
Connecting this to the DOM
First thing to note is that document.write is nearly always a bad idea. Instead, why not give our Elements some unique id attributes and use DOM methods in JavaScript after the Elements exist.
PreviousNext!
So now we can access the first
in JavaScript as document.getElementById('output'), and the two s similarly.
Now, let’s set the initial text in the
, this is quite easy
document.getElementById(‘output’).textContent = arr[0]; // initial value
// if i is still at it’s default value, we could have used i instead of 0
Next, we need to add event listeners to the s so they perform an action. The handler of each will set the text of the
in a similar way to above, but using the relevant function from earlier.
document.getElementById(‘prev_button’).addEventListener(
‘click’, // we want to listen for a click
function (e) { // the e here is the event itself
document.getElementById(‘output’).textContent = prevItem();
}
);
document.getElementById(‘next_button’).addEventListener(
‘click’, // we want to listen for a click
function (e) { // the e here is the event itself
document.getElementById(‘output’).textContent = nextItem();
}
);
This is great! Now the only thing left to do is make sure it runs “after the Elements exist”. There are two ways to do this, either by putting the element after the elements it uses, or by listening for the load event on window, i.e.
window.addEventListener(‘load’, function () {
// DOM related JavaScript goes here