DEV Community

thomasvanholder
thomasvanholder

Posted on

Smooth Scroll Stimulus

Orginally published at Medium on Feb 28th 2020.

Elegantly slide to a section of a page
Smooth scroll

  1. Install the package
  2. Add Stimulus Scroll-To library
  3. Add sidebar
  4. Add content

Learn how to set up a smooth scrolling with Ruby on Rails and Stimulus Components. This is a simple and clean way to enable users to slide to a different section of a page.


Before You Start

Make sure you have Stimulus installed. Check the package.json file or run yarn why stimulus. If Stimulus is not yet installed, follow the documentation.


1. Install the package

Add Stimulus ScrollTo to your project

yarn add stimulus-scroll-to
Enter fullscreen mode Exit fullscreen mode

2. Add Stimulus Scroll-To library

import { Application } from 'stimulus'
import { ScrollTo } from 'stimulus-scroll-to'

const application = Application.start()
application.register("scroll-to", ScrollTo)
Enter fullscreen mode Exit fullscreen mode

3. Add sidebar

Sidebar img

<div class="flex">
  <div class="w-1/5">
    <small class="pb-3 text-sm italic">click a link in the sidebar 👇</small>
    <ul class="sticky flex flex-col w-full h-auto p-2 space-y-4 bg-white border-4 border-gray-500 rounded-lg top-16">
      <li><%= link_to "Introduction", "#introduction", data: {controller: "scroll-to"}  %></li>
      <li><%= link_to "Technical Overview", "#technical_overview", data: {controller: "scroll-to"}  %></li>
      <li><%= link_to "Philosophy & Design", "#philosophy_design", data: {controller: "scroll-to"}  %></li>
      <li><%= link_to "Framework Structure", "#framework_structure", data: {controller: "scroll-to"}  %></li>
      <li><%= link_to "Trademarks", "#trademarks", data: {controller: "scroll-to"}  %></li>
    </ul>
  </div>

  <div class="w-4/5"></div>
</div>

Enter fullscreen mode Exit fullscreen mode
  • data-controller=”scroll-to” scopes the imported controller to every individual link_to.
  • The hashtag(#) in the link_to will look on the same page for a matching id. From #introduction to id=”introduction”

4. Add content

<div class="w-4/5">
  <article>
    <ul>
      <li>
        <p id="introduction">Introduction</p>
        <p>PARAGRAPH HERE</p>
      </li>
      <li>
        <p id="techincal_overview">Techincal Overview</p>
        <p>PARAGRAPH HERE</p>
      </li>
      ...
    </ul>
  </article>
</div>
Enter fullscreen mode Exit fullscreen mode

Note that the code snippet above is a simplified, without Tailwind CSS classes, in order to keep the view clean

That’s it, Smooth Scrolling is now functional!

Thanks for reading!

Top comments (1)

Collapse
 
davidmroz profile image
DavidMroz

it is good in using , keep posting such valuable article which inspire us to do work more . sihr of separation