Giter Club home page Giter Club logo

toc's Introduction

TOC npm

TOC is a library that will automatically generate a table of contents for your page.

Features

  • Completely customizable
  • Click to smooth scroll to that spot on the page
  • Automatically highlight the current section
  • Can have multiple on a page

Installation

npm install import '@firstandthird/toc'

Usage

Import required scripts:

import '@firstandthird/toc';
// or
import Toc from '@firstandthird/toc';

Setup HTML:

<div class="toc" data-toc="h1">

<h1 data-toc-title="Heading 1">My heading</h1>

Options

Options are set via custom properties:

Property Value Description
data-toc {string|Element|NodeList} Elements to use as headings
data-toc-container {string|Element|NodeList} Element to find all selectors in
data-toc-offset {string|Element|NodeList} Offset to trigger the next headline
data-toc-title {string} Text to be used as title (add this to headings)

Example

Example HTML:

<!DOCTYPE HTML>
<html>
  <head>
    <title>TOC Example</title>
    <link href="styles.css" rel="stylesheet" type="text/css">
  </head>
  <body>
    <div class="toc" data-toc="h1, h2, h3"></div>

    <div id="wrapper">
      <h1 data-toc-title="Custom toc title">Page Title</h1>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum fermentum ligula a augue sollicitudin a tincidunt felis tincidunt. Donec et urna augue, sed consectetur lacus. Maecenas tincidunt volutpat lorem. Suspendisse turpis tellus, sodales ac commodo id, rhoncus vel augue. Vestibulum nisl nibh, rutrum eu bibendum vitae, bibendum et libero. Suspendisse vel odio vitae leo commodo lacinia. Sed non lacinia nulla. Pellentesque faucibus euismod dictum. Suspendisse potenti.</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum fermentum ligula a augue sollicitudin a tincidunt felis tincidunt. Donec et urna augue, sed consectetur lacus. Maecenas tincidunt volutpat lorem. Suspendisse turpis tellus, sodales ac commodo id, rhoncus vel augue. Vestibulum nisl nibh, rutrum eu bibendum vitae, bibendum et libero. Suspendisse vel odio vitae leo commodo lacinia. Sed non lacinia nulla. Pellentesque faucibus euismod dictum. Suspendisse potenti.</p>
      <h2>Sub Heading</h2>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum fermentum ligula a augue sollicitudin a tincidunt felis tincidunt. Donec et urna augue, sed consectetur lacus. Maecenas tincidunt volutpat lorem. Suspendisse turpis tellus, sodales ac commodo id, rhoncus vel augue. Vestibulum nisl nibh, rutrum eu bibendum vitae, bibendum et libero. Suspendisse vel odio vitae leo commodo lacinia. Sed non lacinia nulla. Pellentesque faucibus euismod dictum. Suspendisse potenti.</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum fermentum ligula a augue sollicitudin a tincidunt felis tincidunt. Donec et urna augue, sed consectetur lacus. Maecenas tincidunt volutpat lorem. Suspendisse turpis tellus, sodales ac commodo id, rhoncus vel augue. Vestibulum nisl nibh, rutrum eu bibendum vitae, bibendum et libero. Suspendisse vel odio vitae leo commodo lacinia. Sed non lacinia nulla. Pellentesque faucibus euismod dictum. Suspendisse potenti.</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum fermentum ligula a augue sollicitudin a tincidunt felis tincidunt. Donec et urna augue, sed consectetur lacus. Maecenas tincidunt volutpat lorem. Suspendisse turpis tellus, sodales ac commodo id, rhoncus vel augue. Vestibulum nisl nibh, rutrum eu bibendum vitae, bibendum et libero. Suspendisse vel odio vitae leo commodo lacinia. Sed non lacinia nulla. Pellentesque faucibus euismod dictum. Suspendisse potenti.</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum fermentum ligula a augue sollicitudin a tincidunt felis tincidunt. Donec et urna augue, sed consectetur lacus. Maecenas tincidunt volutpat lorem. Suspendisse turpis tellus, sodales ac commodo id, rhoncus vel augue. Vestibulum nisl nibh, rutrum eu bibendum vitae, bibendum et libero. Suspendisse vel odio vitae leo commodo lacinia. Sed non lacinia nulla. Pellentesque faucibus euismod dictum. Suspendisse potenti.</p>
      <h2>Sub Heading</h2>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum fermentum ligula a augue sollicitudin a tincidunt felis tincidunt. Donec et urna augue, sed consectetur lacus. Maecenas tincidunt volutpat lorem. Suspendisse turpis tellus, sodales ac commodo id, rhoncus vel augue. Vestibulum nisl nibh, rutrum eu bibendum vitae, bibendum et libero. Suspendisse vel odio vitae leo commodo lacinia. Sed non lacinia nulla. Pellentesque faucibus euismod dictum. Suspendisse potenti.</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum fermentum ligula a augue sollicitudin a tincidunt felis tincidunt. Donec et urna augue, sed consectetur lacus. Maecenas tincidunt volutpat lorem. Suspendisse turpis tellus, sodales ac commodo id, rhoncus vel augue. Vestibulum nisl nibh, rutrum eu bibendum vitae, bibendum et libero. Suspendisse vel odio vitae leo commodo lacinia. Sed non lacinia nulla. Pellentesque faucibus euismod dictum. Suspendisse potenti.</p>
      <h3 id="last" data-toc-title="Custom subsub-heading">SubSub Heading</h3>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum fermentum ligula a augue sollicitudin a tincidunt felis tincidunt. Donec et urna augue, sed consectetur lacus. Maecenas tincidunt volutpat lorem. Suspendisse turpis tellus, sodales ac commodo id, rhoncus vel augue. Vestibulum nisl nibh, rutrum eu bibendum vitae, bibendum et libero. Suspendisse vel odio vitae leo commodo lacinia. Sed non lacinia nulla. Pellentesque faucibus euismod dictum. Suspendisse potenti.</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum fermentum ligula a augue sollicitudin a tincidunt felis tincidunt. Donec et urna augue, sed consectetur lacus. Maecenas tincidunt volutpat lorem. Suspendisse turpis tellus, sodales ac commodo id, rhoncus vel augue. Vestibulum nisl nibh, rutrum eu bibendum vitae, bibendum et libero. Suspendisse vel odio vitae leo commodo lacinia. Sed non lacinia nulla. Pellentesque faucibus euismod dictum. Suspendisse potenti.</p>
      <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum fermentum ligula a augue sollicitudin a tincidunt felis tincidunt. Donec et urna augue, sed consectetur lacus. Maecenas tincidunt volutpat lorem. Suspendisse turpis tellus, sodales ac commodo id, rhoncus vel augue. Vestibulum nisl nibh, rutrum eu bibendum vitae, bibendum et libero. Suspendisse vel odio vitae leo commodo lacinia. Sed non lacinia nulla. Pellentesque faucibus euismod dictum. Suspendisse potenti.</p>
    </div>
    <script src="scripts.js"></script>
  </body>
</html>

Example JavaScript:

import '@firstandthird/toc';

Example CSS:

.toc {
    background: #fefefe;
    width: 200px;
    position: fixed;
    border: 1px solid #ddd;
    color: #333;
}
.toc a {
    color: #333;
}
.toc .toc-h2 {
    margin-left: 10px
}
.toc .toc-h3 {
    margin-left: 20px
}
.toc-visible {
    color: #000;
    font-weight: bold;
}
.toc.right {
    right: 0
}

License

MIT License

Copyright (c) 2018 First+Third

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

toc's People

Contributors

alejandroperezmartin avatar allspiritseve avatar antonio-laguna avatar dawnerd avatar dtaylor avatar dvberkel avatar edewit avatar inadarei avatar jgallen23 avatar knalli avatar schmunk42 avatar wheresrhys avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

toc's Issues

Support module import

Currently, if I pull this repo, I can't actually import it as a module. I have to make some changes to the top, ex.

  var exports = module.exports = (function () {

It'll be great we can have some dynamic detection if a module or browser is requesting this file. Thank you very much, really liked this piece of work.

Prefix Anchorname with '/'

I have an angularjs app and I am using #toc for generating tabel of contents.

I have my hash urls that starts with #/

It looks fine but when navigating to toc anchors, hash url changes only #, this causes me 404 redirection if I want to navigate to other pages starting with #/some-pages

For this I had prefixed toc anchors with
prefix : '/'
but I get Uncaught Error: Syntax error, unrecognized expression: #/toc-historical-spot,

is there anyway I can fix this.

Thanks in advance.

Anchor link with complete URL

Hi,

thanks for this neat script. Using a CMS I need to add the URL to the anchor name in the link, so I changed line 70 from
.attr('href', '#' + anchorName)
to
.attr('href', window.location + '#' + anchorName).

EDIT:
The above change of code seemed to be working well at first, but now I realise that something isn't working well. Clicking on another link now, the anchor is being added to the URL - http://mydomain.com/mypage.html#toc38#toc19. Refreshing the page adds yet another anchor to the URL etc.

Did I trigger this behavior by adding window.location? Is there a solution for this?

I'd very much appreciate your help,
Anke

Issue in Safari

Hi there!

I found that in Safari on latest version, you get an error when you do the following: First you start scrolling till one of the elements is highlighted, then you try to click an element and it should begin the scrolling but the following error arises:

TypeError: 'undefined' is not a function (evaluating 'scrollable.animate')

It seems that it loose the value of the scrollable within the closure.

I've added this before the animate call and the issue is solved. If anyone knows a better solution it will be greatly appreciated:

if (!scrollable){
    scrollable = findScrollableElement(opts.container, 'body', 'html');
}

On Selected

I want to handle on selected event . it is not working . What am I doing wrong?

              $('#pageContents').toc({ 
                      'smoothScrolling': function(target, options, callback) {
                        $(target).smoothScroller({
                          offset: options.scrollToOffset
                        }).on('smoothScrollerComplete', function() {
                        console.log('asds');
                        $('#pageContents').sly('toEnd', $('#pageContents').find('.toc-active'))
                            callback();
                        });
                     }
            });

[Q] How do i set the Offset from the link

Im wondering how i can set the offset, i wont the link to scroll say 40-80px from the top. But i see 3 different offsets, and 2 dont seem to have any influence?

The offset highlight seems to do something, that does look when the link is X px from the top.

I dont see what the other 2 do. 1 Note this is the version from an different branch, the main branch is missing almost all files.

screen shot 2018-04-20 at 12 13 15 am

screen shot 2018-04-20 at 12 13 01 am

Screen position of selected item

When you click in a item X, it moves the page to the section X, but the header is hidden because the the was moved too far by down. It would be good (at least with a custom property) to appears the header always.

Breaks on some mobile devices in landscape mode

Summary

If you initialize in landscape mode, the script appears to break within the scrollTo function, probably because the scrollable variable is undefined in this scenario.

Affected Devices/Browsers

  • iPad 3 running iOS 5
  • Android 2.3 device (Motorola Droid 3)

Where is the dist folder?

Seems like the compile versions are no longer included in this repo ... Would be nice to have those around as it's a bit of a showstopper for n00bs!

Verbose ids based on heading text

So that internal links to headings can be written into the page's html it'd be useful if there was an option such as verbose-ids: true which would

  1. Read the heading's text
  2. Clean away any non alphanumeric characters
  3. Replace spaces by hyphens
  4. Use this (possibly prefixed bytoc-) as the id

If I get time this week I'll have a go at developing this myself and opening a pull request if you're open to the idea?

There's of course an issue with ensuring uniqueness of ids, but could be tackled by using the entire hierarchy as the id {{verbose h1}}/{{verbose h2}}... which assumes a good document structure, but as it would be a feature devs would turn on when it suits them I think this woudl be something for each dev to consider for themselves.

Click on headings + scroll disallows highlight

Hi all,

Thanks for this useful plugin! I have a problem when clicking on any heading. Scroll is okay, and highlight also. Nevertheless, if you continue scrolling, related headings are not highlighted.

This issue appears on firefox and Google Chrome.

Someone has the same problem ?

Thanks,

Alexander

Empty headings in TOC

If I have a empty heading in my text, this will also be shown in my table of contents. Is there an easy way to exclude those?

README needs to be updated

There should be a short description on how to get up and running in the README. Is this project currently actively maintained or why are there 15 open Pull Requests?

Focus not handled correctly

If you use only a keyboard, the focus is not correctly handled. If we use http://projects.jga.me/toc/, and tab to download, pressing enter, then tab again brings focus back to the TOC link at the top. If focus was properly handled, pressing tab after enter should place focus on the "production" link. To properly move focus tabindex="-1" must be added to the heading it is jumping to, or the <span> that this plug in creates before the heading.

Don't show hidden sections

Something

...

When this is my CSS:
.special{
display:none;
}

the "Something" header still appears in the table of contents.
(Clicking that item in the table of contents does nothing though.)

Composer integration composer.json

Hi guys,

Currently package is integrated with npm, would it possible to integrate it as well with composer?
By creating a composer.json file, the package could become available to composer package manager.

Thanks in advance to all for your replies.
Cheers!

Production link is still not available

Reopening #66:

https://raw.githubusercontent.com/jgallen23/toc/master/dist/toc.min.js

leads to a 404. Maybe it would be worthwhile to publish the production code on a CDN?

Production downloadable link is missing

Link to download production and development file on the github pages are missing due to dist folder is removed.

https://raw.githubusercontent.com/jgallen23/toc/master/dist/toc.min.js

Could you please add new links or summit this library into cdnjs/jsdelivery?

How to set options?

The download links located here http://projects.jga.me/toc/ return 404.

I managed to install via npm, but when I set the options, using $('#toc').toc(); I get Uncaught TypeError: $(...).toc is not a function.

The example configures the selectors with <div class="toc" data-toc="h1, h2, h3">, and doesn't use any jQuery at all. Is there another example somewhere I can look at to get this working?

[B] Downloads dont contain correct files

I just download it and the example files have wrong links. It seems files are missing.

There is no folder dist and none of the files excist. There a 2 TOC.js files but they give errors if i link it to them.

screen shot 2018-04-19 at 5 25 52 pm

headers shown twice

Toc is working 'almost' perfectly. It works perfect when not logged in (front-end) of website. When logged in the h3-headers are shown twice, h2-header (8 wielen vlechten) is shown once.

<ul id="toc" class="toc" ></ul>

<script> $('#toc').toc({ 'selectors': 'h2, h3, h4, h5, h6', //elements to use as headings 'container': 'body', //element to find all selectors in 'smoothScrolling': true, //enable or disable smooth scrolling on click 'prefix': 'toc', //prefix for anchor tags and class names 'onHighlight': function(el) {}, //called when a new section is highlighted 'highlightOnScroll': true, //add class to heading that is currently in focus 'highlightOffset': 100, //offset to trigger the next headline 'anchorName': function(i, heading, prefix) { //custom function for anchor name return prefix+i; }, 'headerText': function(i, heading, $heading) { //custom function building the header-item text return $heading.text(); }, 'itemClass': function(i, heading, $heading, prefix) { // custom function for item class return $heading[0].tagName.toLowerCase(); } });

screen shot 11-15-16 at 09 03 pm 001
screen shot 11-15-16 at 09 03 pm

Does not scroll in FF and IE10

Clicking on a TOC item will change the URL with the correct hash but will not scroll.

IE9 simply jumps down to hash without smooth scroll.

Let the TOC scroll to the highlighted section if needed [POC solution included]

Hi, and thanks for this great piece of code!

I had a minor issue with a long document, where the TOC (as a sidebar) was not fitting in the screen: then, the highlighted section was not always on screen, which partly defeats the purpose of the "Automatically highlight the current section" feature.

I used the following code to let the table of contents scroll automatically to the highlighted section when it's not visible:

function isElementInViewport (el) {
    // special bonus for those using jQuery
    if (typeof jQuery === "function" && el instanceof jQuery) {
        el = el[0];
    }

    var rect = el.getBoundingClientRect();

    return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
        rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
    );
}

$(function(){
    $('#table-of-contents').toc({
        'onHighlight': function(el) {
        // Scroll to make the element visible if needed.
            if (!isElementInViewport(el)) {
                $('#table-of-contents').animate({
                        scrollTop: el.offset().top
                    }, 2000);
            }
        }
    });
});

It would be nice to have the feature built-in (just a 'highlightAutoScroll' : true passed to toc() for example).

Waiting for that, other people may find the code above useful :-). Feel free to use it.

How to guard against duplicate anchors?

I'm trying to use toc.js with an application that allows users to edit HTML saved in a DB with Summernote, and I'm getting duplicate anchors after I save HTML to the DB and reload the content.

screen shot 2017-01-09 at 5 27 53 pm

Why I'm getting this makes sense. It appears that the HTML is loading, toc.js adds an anchor, and when changes are saved, the anchors are being saved, too. The next time the HTML is edited, the anchor span tags get prepending again. Is there a way that toc.js can use anchor elements that match if they're already in the container element?

Here's how I've got my setup configured.

$('#toc').toc({
        selectors: 'h3,h4,h5,h6',
        container: '.col-sm-9 .note-editable.panel-body',
        prefix: 'toc',
});

"." in the generated IDs

One issue is: if a title have the "." char, the generated ID also have it and the anchor not works.

Great plugin, I use for years!

Missing Files

Looks like a great project!

Just fetched with GitHub Desktop and tried the example. Seems the /dist/ folder is missing. Also cannot seem to locate toc.js?

Or, maybe can only use via npm?

Thanks!

Generation of flat list of ul li has some order problem

ok, seems to me right now, all the toc are collected, ex. h2,h3, but when the li is added one by one, we add all h2 and then all h3. Is this a bug ?

   const selectors = el.dataset.toc.split(',').map(s => s.trim());
   selectors.forEach(selector => {
      const items = find(selector, container);

in the old library, jQuery seems to nail this properly

  var headings = $(opts.selectors, container);

so now I wonder if can the new find take a list of tags?

toc not aware of page url?

I'm adding toc.js to a page at http://localhost:8080/testview?view=dev/styleguide.html, yet the links in the TOC are things like this:

<a href="#toc-atoms">Atoms</a>

Clicking on that link takes me to http://localhost:8080/#toc-atoms in error. I think the links should be like /testview?view=dev/styleguide.html#toc-atoms, instead.

How can this be fixed?

Also, not sure if this is related, but the active state isn't following my scroll, either.

Clicking on menu items that scroll to near the bottom of the document highlight the wrong menu item

Test case:

http://projects.jga.me/toc/#toc0

Click on any menu item that refers to an item that is within one page height of the bottom of the document, so on my screen these include History down to Contributions. It then smooth scrolls down to this item, but then when the menu highlight code kicks in it detects that it is only up to the Example CSS section which is the first section visible on the page.

I'd just test if the page bottom was hit as part of the scroll and if so explicitly set the menu item to highlight the on that was just clicked and not do the current location detection.

Issue with special characters

Hi,

I am using TOC and it's an awesome plugin. However, I have an issue : Some of my headings have accents (é,è, ...), thus the anchor generated is not super clean. Example here : for the heading "Sécurité", the anchor is : #toc-s-curit-. Is there a way to replace letters with accent by letters without accent (so my anchor would become #toc-securite ?

Thanks

Inserting anchor element before headline breaks CSS "+" Selector

Inserting the anchor element before headline introduces an additional element between different headlines and/or paragraphs and headlines which breaks CSS stylesheets using the "+" selector (Select consecutive elements).

Possible Solution: Could the anchor be appended to the headline itself? So instead of <span id="toc4"></span><h3>Options</h3> it would create a <h3>Options<span id="toc4"></span></h3>?

data-toc-title support

if the element has data-toc-title on it, we should use that as the TOC name rather than the text of the element

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.