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:https://julyfx.mystagingwebsite.com/stanford-mba-msx-essay-topic-analysis-examples/ Would anyone happen to have a suggestion? Thank you! Leah

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

$('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .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
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":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
          };
        });
      }
    }
  });
});
</script>

Answers:

Answer

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

becomes

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.

Answer

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?

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.