Problem with scrollto offset javascript because of header

I need help with this scrollto code snippet. The problem is that I need to set an offset to account for my menu. Without the offset the header that I scroll to gets buried underneath the menu. See for yourselves here: Would anyone happen to have a suggestion? Thank you! Leah

<script type="text/javascript">
jQuery(document).ready(function($) {

  // Remove links that don't actually link to anything
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          if ($":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again



Should be relatively easy: If your header is for example 85px high, you can just add these 85px to the offset in your code, so this line

scrollTop: target.offset().top


scrollTop: target.offset().top - 85

that way the window will scroll 85px less than calculated, so the section will not be hidden behind the header.


Just a suggestion have you tried something like:

window.scrollTo({top: (jQuery('#2').position().top-jQuery('header').height()), behavior: 'smooth' })


Where #2 would be taken from your this.hash target above?


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.