JTFDI Library
just the focus do it    •    
Creator Economy
       •       
Media
       •       
Marketing
       •       
Eating & Drinking
       •       
Commerce
       •       
Customer Relationships
       •       
Reading
       •       
Tech-stack
       •       
Productivity
       •       
Startup
       •       
Technology
       •       
Business
       •       
•    just the focus do it    •     just the focus do it    
Docs
Mag
Writing
Blog
Try it for Free

Smooth Scrolling to the Next Section with JavaScript and [foo](#next) markdown syntax

2023-04-23
, most recent update.

When I write [foo](#next) markdown syntax in my content I want the reader to jump to the next section, the next anchor, on my webpage.

I want people to be able to skip longer content and "jump to the next section" on my blog posts or webpages, i.e., skipping the introduction.

This should improve the user experience and make it easier for my readers to navigate through my content.

Because, I often fail to write for the one reader across my content. While it is important to focus on one reader, often it comes that you attract more than one reader, especially when you:

  • write for yourself across a wider range of topics
  • write along different developmental journeys and knowledge stages
  • you don’t have an editor,

So you want o make it as easy as possible for those who just came for the recipe to skip to the meat on the bone.

Starting position

  • I use Webflow, WebflowCMS, static sites and DecapCMS (formerly NetlifyCMS) and markdown.
  • For my automatically generated TOC, I already have created anchor links in my blog post using Markdown and HTML.
  • When I write [foo](#next) markdown syntax in my content I want the reader to jump to the next section, the next anchor, on my webpage.

Why this implementation?

The elegant thing about this approach here is, that we do not need an onclick attribute for our links in our blog posts to call the jumpToNextAnchor() function when clicked.

Instead we accomplish the “jumping to the next section” behavior without having to explicitly define the ID for each anchor.

We basically reserve the [foo](#next) syntax, on all the pages where we include our JavaScript solution. It will modify the behavior of all links with a #next href attribute on that page.

Implementation

My current script already generates a table of contents (TOC) by iterating over all h2, h3, and h4 elements and creating corresponding anchor links with unique IDs.

Adding an anchor class

To integrate the [foo](#next)solution with my existing TOC code, I have to modify my existing script to add an anchor class to each heading, that I can later use for the [foo](#next) functionality.

document.getElementById("content").querySelectorAll("h2,h3,h4").forEach(function(heading) {
  let headingText = heading.innerHTML.trim().toLowerCase();
  headingText = headingText.replace(/[^a-z0-9\s]+/gi, '').replace(/\s+/g, '-');
  heading.setAttribute("id", headingText);

// Add the anchor class to the heading heading.classList.add("anchor");

const item = document.createElement("a"); item.innerHTML = heading.innerHTML; item.setAttribute("class", "tocitem"); item.setAttribute("href", "#" + headingText); document.querySelector("#toc").appendChild(item); });

JavaScript for Behavior of #next href attribute

Next we want to modify the behavior of all links with a #next href attribute on the page.

When I use the foo syntax in my blog post, the link will jump to the next section.

For that we want to find the current section's heading based on the scroll position and then jump to the next heading on the page.

document.addEventListener('DOMContentLoaded', function() {
  const nextLinks = document.querySelectorAll('a[href="#next"]');

nextLinks.forEach(function(link) { link.addEventListener('click', function(event) { event.preventDefault(); jumpToNextAnchor(); }); }); });

function jumpToNextAnchor() { const anchors = Array.from(document.getElementsByClassName("anchor")); const currentScrollPosition = window.pageYOffset || document.documentElement.scrollTop; let currentAnchor;

// Find the current anchor based on scroll position for (let i = 0; i < anchors.length; i++) { if (anchors[i].offsetTop > currentScrollPosition) { currentAnchor = anchors[i]; break; } }

// If a current anchor is found, jump to the next anchor if (currentAnchor) { const nextIndex = anchors.indexOf(currentAnchor) + 1; if (nextIndex < anchors.length) { window.scrollTo({ top: anchors[nextIndex].offsetTop, behavior: 'smooth' }); } } }

Bonus:

As you can see, we added a little nice smooth scrolling to the foo function as well.

Now, when you click on a foo link, the page will smoothly scroll to the next section, just like with the TOC function.

Conclusion

Now, you can use the foo syntax in your blog post, and the JavaScript code will modify the behavior of these links to jump to the next heading (anchor) on the page:

I want to add [foo](#next) to my blog post.

Section 1

This is the content of section 1.

Section 2

Skip the boring, jump to the interesting section of my article. This is the boring content of section 2.

Section 3

This is the interesting content of section 3.

This approach will ensure that all links with #next as the href will jump the reader to the next heading on the page.

Read next in DOCU

Displaying Both the Publication and Update Dates on Webpages

Showing both the update and the publish date on your blog / web page seems to be difficult for Search Engines and therefore it seems like only displaying “last updated” is the safer way. If your blog shows more than one date, you are probably confusing Google.

Read next in DOCU

Localization: The "hreflang" Tag Accross Different Domains

John Mueller on how to use the hreflang tags across domains for the localization schemas: It doesn't matter if it's all on one domain or across multiple domains. It should just be one clear place per country and language.

Read next in DOCU

DecapCMS Markdown Guide: Handling URLs with Parentheses for Text Fragment Highlighting

Are broken links in your DecapCMS Markdown articles giving you a headache? never let parentheses break your links again: handle text fragment highlighting in Markdown. No more parentheses-induced troubles in your Github articles built with Netlify!

Read next in DOCU

Leveraging a Small JavaScript for a Quick Multilingual Strategy in Webflow

A button that appears when there is an alternate language defined for your content, making your cotent more relevant to your users experiences. Implementing a Dynamic Language Switcher Button with JavaScript

Read next in DOCU

Interactive URL Copy Feature in Webflow Using Clean JavaScript and Clipboard API

An interactive URL copy feature in Webflow. Using clean JavaScript and the powerful Clipboard API, making it easier for visitors to share your pages. Because who doesn’t appreciate a great user experience?

Read next in DOCU

An Extensive Dynamic Table of Contents Generator for Webflow CMS

Boost your Webflow Blog's readability and SEO with a dynamic Table of Contents (ToC) generator. It automatically creates a stylable, navigable ToC from your headings, and enhances user experience by highlighting the active section during scrolling.

Read next in DOCU

Styling Our Auto-Generated ToC in Webflow

Read next in DOCU

Creating or Changing Slugs in DecapCMS (formerly Netlify CMS)

Changing the URL Slug of your post in DecapCMS in config.yaml using the slug key and name key

Read next in DOCU

Smooth Scrolling to the Next Section with JavaScript and [foo](#next) markdown syntax

When I write [[`foo`](#next)`](#next)` markdown syntax in my content I want the reader to jump to the next section, the next anchor, on my webpage.

Read next in DOCU

Vimeo vs YouTube Embed for your Website

Consider this when you decide between YouTube or Vimeo for Website embeds

Read next in DOCU

Editorial Workflow in Decap CMs (formerly Netlify CMS)

Read next in DOCU

README for ChatGPT and How to Write the Best Prompts

When answering prompts, does it help ChatGPT to be more specific and precise if you give it a set of definitions upfront?

Read next in DOCU

Use Hash-symbol vs Triple-quotes Syntax for Commenting Python Code

Consider this when you choose the syntax for commenting code in Python

Read next in DOCU

Dynamically Generated ToC with Webflow CMS

Generating ToC’s based on h2 and h3 headings of a rich text CMS element with active states in a sticky Table of Contents

Read next in DOCU

Dynamic Social Media Share Buttons for Webflow CMS Blogposts

Add a Twitter button and a share on LinkedIn to your blogposts with sharing content generated from Webflow CMS

Read next in DOCU

Calculate Read Time from Webflow CMS

Calculated a read time from Webflow CMS and add to your blog template.

Read next in DOCU

Add Copy-able Code Blocks to Webflow CMS

Uses highlight.js and custom code to add code blocks where you can copy the code to rich text element of Webflow CMS

Hej. I am on Twitter, too.

Connect with me on Twitter and LinkedIn.