0

I have a small fiddle I was experimenting with, and I noticed calling a function inside a for loop condition was stopping the loop. Basically, initially I wanted to do this:

// add event listeners to tabs
for (i=0;i<tabs.length;i++) {
    tabs[i].addEventListener('click', function(event) {
        var tab = event.target;
        selectPage(tab.dataset.tab);
        changeTab(tab);
    });
    if (tabs[i].classList.contains('active')) {
        selectPage(tabs[i].dataset.tab);
    }
}

But, ended up having to do this to make it work:

// add event listeners to tabs
for (i=0;i<tabs.length;i++) {
    tabs[i].addEventListener('click', function(event) {
        var tab = event.target;
        selectPage(tab.dataset.tab);
        changeTab(tab);
    });
}
// find active class and set page
for (i=0;i<tabs.length;i++) {
  if (tabs[i].classList.contains('active')) {
     selectPage(tabs[i].dataset.tab);
  }
}

Here is a link to the Fiddle

Thanks for any help in advance, I feel there is something fundamental here I'm not getting. Thanks

3
  • That's impossible! Commented Dec 31, 2017 at 2:25
  • Ok, could you explain... Commented Dec 31, 2017 at 2:26
  • Look at my answer Commented Dec 31, 2017 at 2:44

2 Answers 2

1

Lesson 0: use ESLint or similar tools to check your code for trivial errors before spending sleepless nights here on SO and/or in debugging tools.

Lesson 1: localize your variables.

Your problem is with variable i that's global - hence reused by both your global code and selectPage function. The latter sets its value to tabs.length, ending up the loop prematurely.

Just replace i = 0 with var i = 0 at each for expression.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, for the thorough answer, explanation, and suggesting using ESLint!
1

Try declaring the x variable using let.

// add event listeners to tabs
for (let i=0;i<tabs.length;i++) {
    tabs[i].addEventListener('click', function(event) {
    var tab = event.target;
    selectPage(tab.dataset.tab);
    changeTab(tab);
  });
  if (tabs[i].classList.contains('active')) {
    selectPage(tabs[i].dataset.tab);
  }
}

2 Comments

up for suggesting let
Thanks, for the suggestion. I changed vars to let. I'm brushing up on Vanilla JS while learning React, I have become to reliant on jQuery.

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.