1

Something is wrong with the i variable. I can`t figure out what is actually wrong.

for (var i = 0; i < anchors.length; i++) {
  $("." + anchors[i]).click(function() {
    $("body").animate({
      scrollTop: $("#" + anchors[i] + "Strip").offset().top // here an error
      // says that "top" is undefined
    }, 1000);
  });
}
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 1
    make sure `$("#" + anchors[i] + "Strip")` is not null – flyingfox Jul 21 '21 at 08:17
  • 1
    `says that "top" is undefined` are you sure? Please provide a [mcve] with verbatim error message. Probably something else is undefined. `top` being `undefined` would not cause an error. –  Jul 21 '21 at 08:18
  • `i` will be the same as `anchors.length` by the time you click on whatever you click on … and that will always be `undefined` – Quentin Jul 21 '21 at 08:19

1 Answers1

0

The issue is because i will contain the final value set by the for loop when the click event occurs. To fix this you can use a closure.

However, a better approach is to avoid the issue by removing the need for the for loop completely. You can do this by using a single common class on all the elements instead of an incremental one:

$('.anchor').click(e => {
  e.preventDefault();
  let target = $(e.target).attr('href');
  
  $('html, body').animate({
    scrollTop: $(target).offset().top - 10
  }, 1000);
});
.links {
  position: fixed;
  top: 10px;
  left: 10px;
}

.content { 
  margin: 0 0 1000px 100px; 
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="links">
  <a href="#foo" class="anchor">Go to #foo</a><br />
  <a href="#bar" class="anchor">Go to #bar</a>
</div>

<div class="content" id="foo">Foo</div>
<div class="content" id="bar">Bar</div>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339