Question

I'm trying to target anchors inside a div using a smooth scroll script. The issue is that the links aren't targeting the correct anchor points. I have it sort of working. Thoughts?

Fiddle: http://jsfiddle.net/YtJcL/691/

I'm basically using this script:

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('#wrapper').animate({
          scrollTop: target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});
Was it helpful?

Solution

I found the answer:

Updated Fiddle: http://jsfiddle.net/YtJcL/694/

Reference: Smooth scrolling within element, only first link/anchor works

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('#wrapper').animate({
          scrollTop: $('#wrapper').scrollTop() + target.offset().top
        }, 1000);
        return false;
      }
    }
  });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top