Jump to content
Search Community

ScrollTo content nested inside a div

dansmad test
Moderator Tag

Recommended Posts

I am losing my mind 🤪 ScrollTo keeps scrolling the whole page not the # targeted sections i am using  the demo code!!!!

I know i am missing something but for the life of me cant figure it out

 

<div class="w3-col w3-padding-64" style ="width:150px">
        <a href="#section1">Section 1</a>
        <a href="#section2">Section 2</a>
        <a href="#section3">Section 3</a>
        <a href="#section4">Section 4</a>
        <a href="#section5">Section 5</a>
</div>
<div class="w3-row">
  <div class="w3-col"style = "width:150px">
    background_image
    </div>
  <div class="w3-quarter w3-padding-64">
  <section id="section1">Section 1</section>
  <section id="section2">Section 2</section>
  <section id="section3">Section 3</section>
  <section id="section4">Section 4</section>
  <section id="section5">Section 5</section>
  </div>
 </div>
<!--scrollto-->
<script>
gsap.registerPlugin(ScrollToPlugin)
 
function getSamePageAnchor (link) {
  if (
    link.protocol !== window.location.protocol ||
    link.host !== window.location.host ||
    link.pathname !== window.location.pathname ||
    link.search !== window.location.search
  ) {
    return false;
  }
  return link.hash;
}
// Scroll to a given hash, preventing the event given if there is one
function scrollToHash(hash, e) {
  const elem = hash ? document.querySelector(hash) : false;
  if(elem) {
    if(e) e.preventDefault();
    gsap.to(window, {scrollTo: elem});
  }
}
// If a link's href is within the current page, scroll to it instead
document.querySelectorAll('a[href]').forEach(a => {
  a.addEventListener('click', e => {
    scrollToHash(getSamePageAnchor(a), e);
  });
});
// Scroll to the element in the URL's hash on load
scrollToHash(window.location.hash);
</script>
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...