Skip to content

Instantly share code, notes, and snippets.

@dropways
Created March 13, 2024 07:43
Show Gist options
  • Save dropways/d3b39b410f64ff59d452d9464477a2c4 to your computer and use it in GitHub Desktop.
Save dropways/d3b39b410f64ff59d452d9464477a2c4 to your computer and use it in GitHub Desktop.
Click to scroll section id and window hash id scroll on load

Click to scroll section id and window hash id scroll on load

HTML

<ul>
    <li><a href="#section1" class="go-scroll">section1</a></li>
    <li><a href="#section2" class="go-scroll">section2</a></li>
    <li><a href="#section3" class="go-scroll">section3</a></li>
    <li><a href="#section4" class="go-scroll">section4</a></li>
</ul>

<section id="section1"> ..... </section>
<section id="section2"> ..... </section>
<section id="section3"> ..... </section>
<section id="section4"> ..... </section>

jQuery

jQuery(function () {
  jQuery(".go-scroll").on("click", function () {
    jQuery("html, body").animate(
      {
        scrollTop: jQuery(jQuery.attr(this, "href")).offset().top - 80,
      },
      1500
    );
  });
  if (window.location.hash) {
    scroll(0, 0);
    setTimeout(function () {
      scroll(0, 0);
    }, 1);
  }
  setTimeout(() => {
    if (window.location.hash) {
      jQuery("html, body").animate(
        {
          scrollTop: jQuery(window.location.hash).offset().top - 80,
        },
        1000
      );
    }
  }, 1500);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment