user824624
user824624

Reputation: 8080

using gsap to scroll to certain element with element id in a html div container

this is a html container with a list of elements, additionally it is made to overflow-y-auto with a y axis scrolling bar.

<div id="container" class="overflow-y-auto h-screen">
  <div id="element-1">  </div>
  <div id="element-2">  </div>
  <div id="element-3">  </div>
  <div id="element-4">  </div>
  .....
 </div>

what I want to do is to click any element in the html container, and the scrolling bar would automatically locate and scroll to that location.

I tried to implement it in gsap as followed

const scrollTo = ( id : string) => {
    console.log('scrollTo',id);
   gsap.to("#container", {
    scrollTo: { id: id }, // 'element4'
    duration: 1
    });
}

but it didn't work, wondering what is the best way to do it in gsap

Upvotes: 0

Views: 32

Answers (1)

Ezra Siton
Ezra Siton

Reputation: 7781

Your code do not match the API structure:

1/3 Load the plugin code (CDN example):

<!-- GSAP -->
<script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/gsap.min.js"></script>
<!-- ScrollToPlugin -->
<script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/ScrollToPlugin.min.js"></script>

2/3.Register the plugin:

 gsap.registerPlugin(ScrollToPlugin)

3/3.gsap.to window:

// scroll to the element with the ID "#someID"
gsap.to(window, { duration: 2, scrollTo: "#someID" });

Docs: https://gsap.com/docs/v3/Plugins/ScrollToPlugin/

"hello world" Code snippet example:

  gsap.to(window, { duration: 2, scrollTo: "#element-3" });
[vh]{
  min-height: 50vh;
  font-size: 4rem;
}

[vh]:nth-child(even){
  background: lightsalmon;
}
<script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/gsap.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/ScrollToPlugin.min.js"></script>

<div id="container" class="overflow-y-auto h-screen">
  <div vh id="element-1">1</div>
  <div vh id="element-2">2</div>
  <div vh id="element-3">3</div>
  <div vh id="element-4">4</div>
  .....
</div>

On click scrollTo section:

  const scroll_to_sections = document.querySelectorAll("[scroll_to]");

  scroll_to_sections.forEach(scroll_to_section => {
    scroll_to_section.addEventListener('click', (event) => {
      scroll_to_section.textContent = `Scroll to: ${event.target.id}`;
      gsap.to(window, { duration: 1, scrollTo: `#${event.target.id}` });
    });
  });
[scroll_to]{
  min-height: 50vh;
  font-size: 2rem;
  cursor: pointer;
}

[scroll_to]:nth-child(even){
  background: lightsalmon;
}
<script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/gsap.min.js"></script>

<script src="https://cdn.jsdelivr.net/npm/gsap@3.12.5/dist/ScrollToPlugin.min.js"></script>

<div id="container" class="overflow-y-auto h-screen">
  <div scroll_to id="element-1">1</div>
  <div scroll_to id="element-2">2</div>
  <div scroll_to id="element-3">3</div>
  <div scroll_to id="element-4">4</div>
  .....
</div>

Upvotes: 0

Related Questions