AnchorJS Table of Contents
Clipboard example
by Bryan Braun
HTML
<script src="https://rawgit.com/bryanbraun/anchorjs/master/anchor.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js"></script>
<div class="jump-nav">
<ul>
<li><a href="#phantom">The Phantom Menace</a></li>
<li><a href="#clones">Attack of the Clones</a></li>
<li><a href="#revenge">Revenge of the Sith</a></li>
<li><a href="#hope">A New Hope</a></li>
<li><a href="#empire">The Empire Strikes Back</a></li>
<li><a href="#return">Return of the Jedi</a></li>
<li><a href="#awakens">The Force Awakens</a></li>
</ul>
</div>
<hr />
<h2 id="phantom">The Phantom Menace</h2>
<p>Sed molestie augue sit amet leo consequat posuere. Vestibulum ante ipsum primis.</p>
<h2 id="clones">Attack of the Clones</h2>
<p>Sed molestie augue sit amet leo consequat posuere. Vestibulum ante ipsum primis.</p>
<h2 id="revenge">Revenge of the Sith</h2>
<p>In pellentesque faucibus vestibulum. Nulla at nulla justo, eget luctus.</p>
<h2 id="hope">A New Hope</h2>
<p>In pellentesque faucibus vestibulum. Nulla at nulla justo, eget luctus.</p>
<h2 id="empire">The Empire Strikes Back</h2>
<p>Vivamus luctus urna sed urna ultricies ac tempor dui sagittis.</p>
<h2 id="return">Return of the Jedi</h2>
<p>Phasellus molestie magna non est bibendum non venenatis nisl tempor. Suspendisse dictum.</p>
<h2 id="awakens">The Force Awakens</h2>
<p>In condimentum facilisis porta. Sed nec diam eu diam mattis viverra.</p>
JavaScript
anchors.options.visible = 'always';
anchors.add('h2');
// add deep anchor link href value to data-clipboard-text attribute for ClipboardJS
for (var r=0; r < document.getElementsByClassName("anchorjs-link").length; r++) {
var danchors = document.getElementsByClassName("anchorjs-link");
var danchorshref = danchors[r].href;
danchors[r].setAttribute('data-clipboard-text',danchorshref);
}
// run this after running AnchorJS
let anchorjsLinks = document.querySelectorAll(".anchorjs-link");
anchorjsLinks.forEach(el => {
el.addEventListener("click", event => {
event.preventDefault();
var clipboard = new ClipboardJS(event.currentTarget);
// add custom "copy to clipboard" code
console.log('clicked ', ClipboardJS);
});
});