Search code examples
htmlhreftableofcontentsjquery-tocify-js

Using href and Tocify toc


I am using Tocify to make a TOC and I'm having some trouble. In this TOC I have: "chapter 1", "chapter 2"...

In my site there are some places when I say "See chapter 1". I have to include "a href" to "chapter 1" in my "See chapter 1" html text. But I don't know what I have to write in that "a href=#....".

How can I do that?


Solution

  • It is done as follows:

    Basically you need to set an ID to a element you want to reference. Then you can write:

    <a href="#id">See chapter ID</a>
    
    <h2 id="chapter1">Chapter 1</h2>
    <p>Your paragraphs</p>
    <p> ... </p>
    <a href="#chapter2">See chapter 2</a>
    
    <h2 id="chapter2">Chapter 2</h2>
    <p>Your paragraphs</p>
    <p> ... </p>
    <a href="#chapter1">See chapter 1</a>
    

    Hope this helps you.

    EDIT:

    Try something like this:

    $(document).ready(function() {
    
      var link = $('#linkId');
    
      var chapter = $('#chapterId');
      var position = chapter.position(); // according to jQuery api
      var offsetTop = position.top; // this should be the absolute offset of the page's top
    
      // Calls the tocify method on your HTML elements.
      link.tocify();
      chapter.tocify();
    
      //Call the tocify method with options
      link.tocify({
        showEffect: "fadeIn"
        scrollTo: offsetTop, 
        smoothScroll: false
      });
    
    • You cannot use tocify and #-href's at the same time because as you saw they override the url. So you have to use a jQuery or tocify method (see api's) to scroll to the specific element.

    • Or you may don't want to use tocify on links.