1

I have this anchor link from Page A, abc.com/news#section2

In news page, the header blocks the top part of the section 2. I tried to offset it in jquery but it doesn't work. Hope someone can help, thanks in advance!

jQuery('.ch-item a').click(function(e) {

    var link = jQuery(this);
    var target = jQuery(link.attr('href').substring(link.attr('href').indexOf('#')));
    if(target.length > 0) {
        jQuery('html, body').stop().animate({scrollTop: target.offset().top - jQuery('.header_container').outerHeight()}, 1000);
        e.preventDefault();
    } else if(options.preventNonLink) {
        e.preventDefault();
    }
});``
Sylph
  • 1,425
  • 3
  • 26
  • 36

2 Answers2

1

give a try to this

$(document).ready(function () {
    $('a[href^="#"]').on('click', function (e) {
        e.preventDefault();
        var target = this.hash;
        var t = $(this.hash).offset().top;
        $('html, body').stop().animate({
        scrollTop: t,
        }, 1000, function () {
            window.location.hash = target;
        });
    });
});
Vitorino fernandes
  • 15,794
  • 3
  • 20
  • 39
1

This is an anchor fix snippet written for jQuery. It fires on page load and if the hash changes (on page anchors).

(function($, window) {
  var adjustAnchor= function() {

    var $anchor = $(':target'),
     fixedElementHeight = 100;

    if ($anchor.length > 0) {

      $('html, body')
        .stop()
        .animate({
          scrollTop: $anchor.offset().top - fixedElementHeight
        }, 200);

    }

  };

  $(window).on('hashchange load', function() {
    adjustAnchor();
  });

})(jQuery, window);

This will examine the URL on page load to see if there is an anchor then adjust the page by 100px off the top of the target.

Edit: adjusted to make the height adjustment obvious

The same Uglified:

!function(o,n){var t=function(){var n=o(":target"),t=100;n.length>0&&o("html, body").stop().animate({scrollTop:n.offset().top-t},200)};o(n).on("hashchange load",function(){t()})}(jQuery,window);
Lance
  • 861
  • 7
  • 12
  • If you don't like the animation, replace the $('html, body')... function with: `window.scrollTo(0, $anchor.offset().top - fixedElementHeight);` – Lance Apr 24 '15 at 16:47