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.
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 is not supported. You can use the CSS rule html { scroll-behavior: smooth; }
or use the onclick option to add custom scrolling behavior.