Navigating through multiple sections by scrolling to the h2 titles

I am in the process of creating an online book that will consist of multiple chapters. In each chapter, I want to include a sidebar with scroll-navigation that automatically links to every h2 heading within that specific chapter.

I have experimented with the scrollnav plugin, but encountered an issue where it generated incorrect links as it was not designed to work with multiple sections (linking to previous sections instead).

Does anyone have a better solution for implementing this feature?

Note: The ebook will be quite lengthy, with around 13-15 chapters and 10-12 subchapters in each. Therefore, having an autogenerated id for the h2 headings (or an alternative solution) would be ideal :-)

The HTML structure is as follows:

<section id="1">
<h2>Sub-chapter 1</h2>
<h2>Sub-chapter 2</h2>
<h2>Sub-chapter 3</h2>
</section>

<section id="2">
<h2>Sub-chapter 1</h2>
<h2>Sub-chapter 2</h2>
<h2>Sub-chapter 3</h2>
</section>

<section id="3">
<h2>Sub-chapter 1</h2>
<h2>Sub-chapter 2</h2>
<h2>Sub-chapter 3</h2>
</section>

Additionally, I should mention that I am still relatively new to working with JavaScript.

Answer №1

// On DOM ready
jQuery(document).ready(function(){
    jQuery('section').each(function(){
        var listHTML = '<ul>';
        var sectionID = jQuery(this).attr('id');
        var count = 1;
        jQuery(this).children('h2').each(function(){
            jQuery(this).attr('id', sectionID + '-' + count);
            listHTML += '<li><a href="#' + jQuery(this).attr('id') + '">' + jQuery(this).text() + '</a></li>';
            count++;
        });
        listHTML += '</ul>';
        jQuery(this).prepend(listHTML);
    });
});

http://jsfiddle.net/sh9xzc2c/

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What sets the Test Deployment and Actual Deployment apart from each other?

I have been developing a web application using Google App Script and I currently have multiple versions of the same web app with various fields. Interestingly, when I run one version through a test deployment, it displays correctly as expected based on th ...

Tips for maintaining state URL persistence after a page refresh in Next.js 13 when utilizing next-usequerystate

Currently, I am using the next-usequerystate library with Next Js 13. However, I have encountered an issue where the state on the URL is lost when I refresh the page. The initial URL looks like this: localhost:3000/?page=1&genres=tree But upon refres ...

I am attempting to establish a connection between a phpMyAdmin database and a node.js application, however, I keep encountering

Currently, I am rebuilding a WordPress website from scratch using React for the frontend and Node.js with Express for the backend. The existing WordPress site has a large number of posts stored in its database, and my goal is to utilize this same database ...

Arrange a div beneath another div that is positioned absolutely

Within my code, I have a div with the property of absolute positioning referred to as "abs". Right after this div, there is another div called "footer" which does not have any specified position value assigned to it. Even though I've experimented with ...

ReactJS popover element - property pushing and event management

I'm currently developing a reactjs application, and I'm working on creating a modular popup component. The goal is to have the button appear as a combination of a badge and an icon, triggering the popup menu on hover rather than on click. Here i ...

"Enhance Your Website with Javascript: Combining and Incorpor

I'm struggling to assign the selected attribute to the option value that is already rendered within the object. However, despite the values being equal, the selected attribute is not being added. Could this issue be related to the appending process? ...

The HTML elements in my JSX code seem to constantly shift around whenever I resize my webpage

Using react.js, I'm currently developing a website that appears like this before resizing: pre-resize_screenshot_website However, upon vertical or diagonal resizing, the layout becomes distorted especially in the 'availability search bar' ...

Can the manifest.json file be edited dynamically?

I'm in the process of developing a React PWA and I'm exploring the possibility of dynamically adding icon URLs to the manifest.json file. My aim is to display a generic app icon until the user logs in. Once logged in, I plan to fetch a new icon f ...

I'm encountering an issue and would appreciate any guidance on resolving it. Specifically, I am receiving the following error message: "localhost/:1 Failed to load resource: the server responded with a

I am currently working on developing my own online multiplayer .io game, inspired by popular games like and . As part of this process, I am setting up a server with the following code: var path = require('path'); var http = require('http&a ...

unable to simultaneously scroll two elements

Within the realm of reactjs, I've crafted a function that smoothly scrolls elements by utilizing a useRef: ref.current?.scrollIntoView({ behavior: "smooth", block: "nearest", inline: "center", }); ...

Avoiding duplicate touch events with an if statement

I am currently working on a module for a responsive website that involves tapping the initial screen to reveal a panel from the right. The user can then tap a close button to hide the panel. However, there is an issue where if the user taps multiple times ...

I have a task of enclosing a table row within a div element

How can I enclose a table row in a div element? $('table tr').each(function(){ $(this).wrap('<div></div>'); }) It seems like my current solution is not working. Can someone help me fix it? UPDATE Fiddle: http://jsfiddl ...

Populating a Textarea Using Javascript Triggered by a Click Event

Currently, I am working on a project that requires a status update. I want to create an onclick event for the select box so that the textarea is only displayed if the user selects "pending" as the status. echo " <select onchange=\"window.location= ...

Is jQuery still recommended for adding animations in VueJS?

In my component's methods object, I currently have the following code snippet: startImageAnimation() { $('.splash-image').fadeIn(1400, () => { setTimeout(function() { $('.splash-image').fadeOut(1400, () ...

Android: A comprehensive look at how Universal Image Loader addresses blank space problems

Currently, I am dealing with a string that includes HTML content like text and images. To properly display the <img> tags in a TextView, I have opted for the Android Universal Image Loader (UIL). Each image should ideally appear in its original posit ...

Showing a Message in Blazor WebAssembly

In Visual Studio 2019 (Blazor Webassembly), I am working on a project where users can insert text, choose a specific time, and set the date. The inserted text will be displayed as entered after the specified time has passed. For example, in the second ima ...

Prevent unauthorized access to my website's code

There are multiple ways for visitors to view the source code of a web page, such as right-clicking and selecting 'view source', or using keyboard shortcuts like ctrl+u, ctr+shft+i, ctrl+shft+j, or f12. I want to give credit where it's due - ...

Ways to verify if an element contains no content and then eliminate that element using jQuery

I am currently attempting to identify any h2 element within a specific div that contains no content and then delete it. Below is the HTML code I am working with: <div class="skipToContainer"> <h2 class="vidSkipTo">Hello </h2> ...

Identifying the index of form inputs and select elements in JavaScript

In my HTML form, I have a mix of inputs and selects that are combined together: <th><input type="text" id="bGroup" name="search_group" /></th> <th><input type="text" id="bEvent" name="search_event" /></th> <th> ...

How to utilize jQuery to eliminate HTML onchange code

This block of code features an HTML onchange attribute as well as the use of jQuery's change event on an input text. I want only the jQuery change event to take precedence. I have attempted to use both unbind and off without success. Can someone prov ...