0
var boks = ['.menu-469', '.menu-471', '.menu-470'];
var element = ['#about', '#slider', '#afisha'];

for (var i = 0; i < 2; i++) {
    $('#main-menu li' + boks[i]).click(function() {
       $(window).scrollTo($(element[i]), 800);
       alert(element[i]);
    });
}

This code is always scrolling to the latest array element in my example it's #afisha. How can i make such functionality - when i click on #main-menu li.menu-469 my page scrolls down to the #about, when i click on #main-menu li.menu-471 it scrolls down to #slider

Thanks in advance

Alexander Kim
  • 17,304
  • 23
  • 100
  • 157

1 Answers1

2

When your for loop has ended the value of i has reached your last index, so you need to create an inner self-executing function (a closure) and pass the actual value of i

for (var i = 0; i < 2; i++) {
    (function(i) {
       $('#main-menu li' + boks[i]).click(function() {
          $(window).scrollTo($(element[i]), 800);
          alert(element[i]);
       });
    }(i));
}
Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177