0

My referenced vars keep getting reset to 0, why? Each section has a set of Previous and Next buttons, initially they work fine but when I return to a section the counter for that section is set to 0. It should retain the number it had been set to previously. Thanks in advance. This is not the actual code being used, but it demonstrates the issue ( I hope )

var currentPageIndex = null;
var section1_count = 0;
var section2_count = 0;
var section3_count = 0;

function checkSectionPage( value ){
    switch(value){
        case "section1":
            currentPageIndex= section1_count;
            break;
        case "section2":
            currentPageIndex= section2_count;
            break;
        case "section3":
            currentPageIndex= section3_count;
            break;
    }
}
$('.slidePrevious').click(function(){
    checkSectionPage($(this).parent().attr('id'));
    currentPageIndex--;
});
$('.slideNext').click(function(){
    checkSectionPage($(this).parent().attr('id'));
    currentPageIndex++;
});
1
  • because you never update section count. It is always zero. Commented Mar 1, 2016 at 13:46

2 Answers 2

1

You never update section#_count. When you set currentPageIndex to the section, the section number does not just increase. You would need to manually update it.

Do something like this:

var activeSection = "section1";
var sects = {
    "section1" : 0,
    "section2" : 0,
    "section3" : 0
};

$('.slidePrevious').click(function(){
    sects[$(this).parent().attr('id')]--;
});
$('.slideNext').click(function(){
    sects[$(this).parent().attr('id')]--;
});
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the quick replies and solutions. Most appreciated.
0

You are not incrementing/decrementing what you think you are.
You want something like:

currentPageIndex = "section1_count";
 ...

window[currentPageIndex]++;

(bare vars, "global variables", in a browser context are actually fields in the window object)

Or to move your counts into an object (like @pascarello's answer) or perhaps into an array, along these lines:

var pageIndexes = [ 0, 0, 0 ];

which = 1;
 ...

pageIndexes[which]++;

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.