Skip to content

Instantly share code, notes, and snippets.

@webketje
Last active January 11, 2019 01:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webketje/b6b3ef5486afd99ff868e8028a0e526c to your computer and use it in GitHub Desktop.
Save webketje/b6b3ef5486afd99ff868e8028a0e526c to your computer and use it in GitHub Desktop.
Anchorize JS - a Javascript plugin which turns HTML headings into clickable anchors for easy bookmarking and navigation

Anchorize.js

Anchorize is a small Javascript module which adds clickable anchors left of headings (or other elements with text contents). Elements without an id will get their first 20 characters slugified as an id. The result is similar to the link icons next to the titles on this file, viewed in Github gists. Demo

Works in browser environment with browser globals, commonJS & AMD.

Usage & options

anchorize('h2,h3');

anchorize({
  root: document.body,
  selector: 'section h2',
  symbol: '#',
  onclick: function(e) {
    // custom logic when a link is clicked (will scroll & add a history entry by default)
  }
});

// prevent changing the URL/ scrolling
anchorize({
  onclick: function(e) {
    e.preventDefault();
  }
})

// prevent changing the URL, but allow scrolling
anchorize({
  onclick: function(e) {
    e.preventDefault();
    e.target.scrollIntoView();
  }
})

Smooth scroll

Smooth scroll is not supported. You can use the CSS rule html { scroll-behavior: smooth; } or use the onclick option to add custom scrolling behavior.

/* AnchorizeJS v0.8 | 2019-01-11 | Kevin Van Lierde (kevin.van.lierde@gmail.com) | MIT license */
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define([], factory);
} else if (typeof module === 'object' && module.exports) {
module.exports = factory();
} else {
root.anchorize = factory();
}
}(typeof self !== 'undefined' ? self : this, function () {
'use strict';
var defaultOptions = {
selector: 'h2,h3',
symbol: '#',
onclick: null
};
function makeAnchorLink(id, symbol) {
var a = document.createElement('a');
a.className = 'anchorize-hash';
a.href = '#' + id;
a.appendChild(document.createTextNode(symbol));
return a;
}
function makeAnchor(el, symbol) {
var a = document.createElement('a');
a.className = 'anchorize-anchor';
a.setAttribute('aria-hidden', 'true');
a.name = slugify(el.id || el.textContent.slice(0, 20));
el.parentNode.insertBefore(a, el);
el.insertBefore(makeAnchorLink(a.name, symbol), el.firstChild);
return a;
}
function slugify(str) {
return str
.toLowerCase()
.replace(/[ _]+/g, '-')
.replace(/[!:^*./\\]/g, '');
}
return function anchorize(opts) {
var options = Object.assign(
{ root: document.body },
defaultOptions,
typeof opts === 'string' ? { selector: opts } : opts
);
var c = options.root.querySelectorAll(options.selector);
for (var i = 0, len = c.length; i < len; i++)
if (!c[i].previousElementSibling || !c[i].previousElementSibling.className.match('anchorize-anchor'))
makeAnchor(c[i], options.symbol);
if (options.onclick)
options.root.addEventListener('click', function(e) {
var target = options.root.querySelector('[name="' + e.target.getAttribute('href').slice(1) + '"]');
if (target && Array.prototype.indexOf.call(c, e.target.parentNode) > -1)
options.onclick(e, target);
});
};
}));
/* AnchorizeJS v0.8 | 2019-01-11 | Kevin Van Lierde (kevin.van.lierde@gmail.com) | MIT license */
!function(e,t){"function"==typeof define&&define.amd?define([],t):"object"==typeof module&&module.exports?module.exports=t():e.anchorize=t()}("undefined"!=typeof self?self:this,function(){"use strict";var c={selector:"h2,h3",symbol:"#",onclick:null};function i(e,t){var o,r,n,c=document.createElement("a");return c.className="anchorize-anchor",c.setAttribute("aria-hidden","true"),c.name=(e.id||e.textContent.slice(0,20)).toLowerCase().replace(/[ _]+/g,"-").replace(/[!:^*./\\]/g,""),e.parentNode.insertBefore(c,e),e.insertBefore((o=c.name,r=t,(n=document.createElement("a")).className="anchorize-hash",n.href="#"+o,n.appendChild(document.createTextNode(r)),n),e.firstChild),c}return function(e){for(var o=Object.assign({root:document.body},c,"string"==typeof e?{selector:e}:e),r=o.root.querySelectorAll(o.selector),t=0,n=r.length;t<n;t++)r[t].previousElementSibling&&r[t].previousElementSibling.className.match("anchorize-anchor")||i(r[t],o.symbol);o.onclick&&o.root.addEventListener("click",function(e){var t=o.root.querySelector('[name="'+e.target.getAttribute("href").slice(1)+'"]');t&&-1<Array.prototype.indexOf.call(r,e.target.parentNode)&&o.onclick(e,t)})}});
/* standard CSS. Add position:relative to elements which get an anchor hash */
html { scroll-behavior: smooth; }
.anchorize-hash { outline: none; text-decoration: none; position: absolute; left: 0; cursor: hand; cursor: pointer; color: inherit; opacity: 0.3; transition: opacity .1s; }
.anchorize-hash:hover { opacity: 1; }
h2, h3 { position: relative; padding-left: 1em; }
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Anchorize.js demo</title>
<link rel="stylesheet" href="CSS.css">
<script src="anchorize.js"></script>
<style>body { line-height: 1.5em; } h3 { margin: 25px 0; } p { margin: 25px 0 150px; }</style>
</head>
<body>
<h2>Level 2 Heading 1</h2>
<h3>Level 3 Heading 1</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<h3>Level 3 Heading 2</h3>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</p>
<h2>Level 2 Heading 2</h2>
<h3>Level 3 Heading 3</h3>
<p>At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.</p>
<h3>Level 3 Heading 4</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<script>
// works with single selector parameter
anchorize('h3');
// can initialize with different parameters on different selectors
anchorize({
selector: 'h2',
symbol: '➞',
onclick: function(e, target) {
e.preventDefault();
target.scrollIntoView();
}
});
// but will not re-initialize over existing elements to prevent duplicates
anchorize('h2,h3');
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment