1

I have 8 boxes that the user can select, if they select box 1 - it should alert that box 1 has been selected. The same applies to all 8 boxes. Right now, I'm running a for loop at an interval of 1/10th of a second, which should check which box is being clicked, and then output the alert based on the switch statement.

When you run the code, it alerts that box 8 has always being selected, and I can't figure out, how to select the box

  • The boxes are empty divs set in the HTML document, with the id referenced in the array

EDIT: The clearInterval(interval); works in it's current position, but on every click outputs an error

"Uncaught ReferenceError: interval is not defined"

^ Any ideas?

Page Load:

$(function() { //On page load
    var interval = setInterval(buttonClick, 100);
});

Button click function

function buttonClick() {

    //INITIALIZING ARRAY
    var displayBox = [$("#boxOne-line-one"), $("#boxTwo-line-one"), $("#boxThree-line-one"), $("#boxFour-line-one"), $("#boxFive-line-one"), $("#boxSix-line-one"), $("#boxSeven-line-one"), $("#boxEight-line-one")];
    var slidePos = 0;

    for (let i = 0; i <= 7; i++) {
  (ii => {
    displayBox[ii].click(function() {
      slidePos = ii;
      console.log(slidePos);
      wbox(slidePos);
      clearInterval(interval);
    });
  })(i);
}
}

Switch statement function, "which box"

function wbox(slidePos) {
        switch(slidePos) {
        case 0:
        alert("BOX 1 SELECTED");
        break;

            case 1:
        alert("BOX 2 SELECTED");
        break;

        case 2:
        alert("BOX 3 SELECTED");
        break;

        case 3:
        alert("BOX 4 SELECTED");
        break;

        case 4:
        alert("BOX 5 SELECTED");
        break;

        case 5:
        alert("BOX 6 SELECTED");
        break;

        case 6:
        alert("BOX 7 SELECTED");
        break;

        case 7:
        alert("BOX 8 SELECTED");
        break;
    }
}

Actual: "BOX 8 SELECTED"
Expected: The correct box

1 Answer 1

1

You need to change your loop to avoid i being global:

for (let i = 0; i < 7; i++) {
  (ii => {
    displayBox[ii].click(function() {
      slidePos = ii;
      console.log(slidePos);
      wbox(slidePos);
      clearInterval(interval);
    });
  })(i);
}
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.