jgallen23 / toc

Table of Contents Plugin

Home Page:http://projects.jga.me/toc/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to guard against duplicate anchors?

steve-kasica opened this issue · comments

commented

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',
});
commented

I found a workaround without having to modify the jQuery widget. Maybe someone will be in a similar situation and find this useful.

toc.js won't append a span tag if the heading's ID matches the result of the anchorName method. So before I initialize toc.js, I preemptively assign all the heading IDs with the anchorName method.

var container = '.col-sm-9 .note-editable.panel-body';
var selectors = 'h3,h4,h5,h6';
var prefix = 'toc';

$(container).find(selectors).each(function(i, heading) {
    if (!heading.id) {
        var anchorName = $.fn.toc.defaults.anchorName(i, heading, prefix);
        $(heading).attr('id', anchorName);
    }
});

// Initialize toc.js as normal.
$('#toc').toc({
    'selectors': selectors,
    'container': container,
    'prefix': prefix,
});