2

This is the next function that i learn from other's post and i wonder how to do the prev function.

any idea guys? Different approach are welcome as well.

function next() {
    var pElems = document.querySelectorAll('#Pages>div');
    for (var i = 0; i < pElems.length; i++) {
        if (pElems[i].style.display !== 'none') {
            pElems[i].style.display = 'none';
            if (i === pElems.length - 1) {
                pElems[0].style.display = 'block';
            } else {
                pElems[i + 1].style.display = 'block';
            }
            break;
        }
    }
}
1
  • Exactly the same, but reverse the array. Or start at the end of the array and do i-- until it's 0. Or use i == pElems.lenghth + 1 in combination with pElems[i - 1].style.display etc. So may possibilities, just play around with it a bit. Commented Dec 23, 2016 at 13:59

1 Answer 1

1

Your current function steps one element forward: pElems[i + 1], so to go backwards you could just step one backwards pElems[i - 1] and then you have to handle the case of reaching the first element and jump to the end, something like this should do it:

function prev() {
    var pElems = document.querySelectorAll('#Pages>div');
    for (var i = 0; i < pElems.length; i++) {
        if (pElems[i].style.display !== 'none') {
            pElems[i].style.display = 'none';
            if (i === 0) {
                pElems[pElems.length].style.display = 'block';
            } else {
                pElems[i - 1].style.display = 'block';
            }
            break;
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.