2
if (btns.length && sections.length > 0) {

  btns[0].addEventListener('click', function (event) {
    smoothScrollTo(sections[0], event);
  });
  btns[1].addEventListener('click', function (event) {
    smoothScrollTo(sections[1], event);
  });
  btns[2].addEventListener('click', function (event) {
    smoothScrollTo(sections[2], event);
  });
  btns[3].addEventListener('click', function (event) {
    smoothScrollTo(sections[3], event);
  });
}

Hello friends lets say I have many more buttons! instead of coding each one of them how to make it in short! I am new in js...

Thanks

messerbill
  • 5,499
  • 1
  • 27
  • 38
  • 3
    Research 'loops in JS' – Rory McCrossan Jan 29 '18 at 10:47
  • 1
    or wait for someone to write the code for you, of course: anyway [loops 101: the for loop](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for) – Jaromanda X Jan 29 '18 at 10:50
  • You can use loop to create an event for each action https://www.w3schools.com/js/js_loop_for.asp – Ajay Singh Deopa Jan 29 '18 at 10:50
  • @AjaySinghDeopa Please don't use W3Schools as a reference. Their articles are often outdated and sometimes just plain wrong. MDN is far more comprehensive and accurate: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for – Rory McCrossan Jan 29 '18 at 10:50
  • Possible duplicate of [Loop through an array in JavaScript](https://stackoverflow.com/questions/3010840/loop-through-an-array-in-javascript) – Pete Jan 29 '18 at 10:51
  • @RoryMcCrossan While I do agree with you it's sometimes hard for new developers to understand the MDN documentation while W3Schools does have a more casual approach for beginners. At least from my perspective. – anteAdamovic Jan 29 '18 at 10:52
  • if you don't mind that `casual approach` === `sometimes just plain wrong`, then it's a good resource – Jaromanda X Jan 29 '18 at 10:52
  • I agree it's more casual, but I'd rather have something accurate that teaches me how to interpret professional specifications, than something easy and wrong. – Rory McCrossan Jan 29 '18 at 10:53

2 Answers2

3

I see a jQuery TAG over there, isn't it?

$(btns).click(function(event) {
    smoothScrollTo(sections[$(this).index()], event);
});

It would be better if you add the index into the button as attribute, or with an ID, to prevent any problem...

SubjectDelta
  • 405
  • 1
  • 3
  • 14
-2

You need to create an anonymous function to pass the i variable.

if (btns.length && sections.length > 0) {
  var l = btns.length;
  for (var i = 0; i < l; i++) {
    btns[i].addEventListener('click', function(event) {
      (function(_i) {
        smoothScrollTo(sections[_i], event);
      })(i);
    });
  }
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
ZiTAL
  • 3,466
  • 8
  • 35
  • 50