bootstrap-toc
bootstrap-toc copied to clipboard
ensure table of contents isn't created twice
Multiple people have run into the issue (#21 and #34), so either the instructions aren't clear enough, or the plugin should Do the Right Thing and not initialize multiple times.
A plugin library should not depend on the sequence of jquery document ready initializations.
If custom code triggers the TOC.init() first, the library creates a DOM element that then results in duplication if your libraries' document ready is triggered. (In our case it's almost impossible to change this sequence..)
The library is missing a protection against such a duplication. This can be achieved as simple as setting a helper class when completing init() that you then exclude in the libraries' document ready or the init() selector itself.
Added a new PR for this https://github.com/afeld/bootstrap-toc/pull/46. :)
I land myself here after debugging this issue for hours. My case is a bit more complicated because I use AJAX to load documents and run Toc.init
with different $scope
but then the library's own init
function will alway add a second Toc.
With CSS, make sure you let bootstrap-toc.min.css
right under bootstrap.min.css
. Do not let any other CSS between them.
<!-- CSS -->
<link type="text/css" rel="stylesheet" href="css/bootstrap.min.css"/>
<link rel="stylesheet" href="css/bootstrap-toc.min.css"/>
With Jquery and JS, make sure you let bootstrap-toc.min.js
right under bootstrap.min.js
. Do not let any other JS between them. And you should place them in the order below.
<!-- Jquery and JS -->
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="js/popper.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/bootstrap-toc.min.js"></script>
And then TOC plugin will work perfectly. That is how I fixed it when TOC is duplicated.
And if above solution does not work, you can try to use JS to remove one of two duplicated TOCs.
$(document).ready(function () {
$("#toc ul").eq(0).remove();
});
I tried, and out of frustration I modified bootstrap-toc.js
to remove the ready()
function just as you have suggested.
When my TOC plugin created two Table of contents instead of one, I checked the .html source in browser's developer mode and I see that it created two <ul>
inside <nav id="toc">
instead of one as expected. So that I use this script to remove one <ul>
and everything work correctly.
And I mean, you should add this script to a custom_script.js
and use this custom_script.js
in .html page where you need to use TOC plugin, instead of modifying bootstrap-toc.js
.