Dynamically Adding "Link To Section" to Heading Tags with Javascript

Dynamically Adding

I often want to link to a part of a blog post that is halfway down the page. Makes for smart content sharing and linking as sometimes a blog post may be 3000+ words long and you can't be bothered scrolling all the way down.

The idea was to dynamically add id's to heading tags and generate a link of the heading that can copy to clipboard the page link and new hashtag.

And for design purposes, on desktop, I wanted to hide the link until a user hovers over the heading.
And for mobile, I simply only displayed the links (without the need for hovering) on heading tags of h2.

Using some sneaky Javascript to simulate a copy to clipboard command, I was able to create a "Copy To Clipboard" link.

function headingLinks(){
var url = document.location;
var hash = url.hash+"";
var url = url+"";
var url = url.replace(hash,'');
var url = url.replace(/(\&|\?)fbclid([_a-z0-9=]+)/g, "");
var url = url.replace(/(\&|\?)utm([_a-z0-9=]+)/g, "");
var count = 0;
var tags = ["h2","h3","h4","h5"];
for (a = 0; a < tags.length; a++) {
var tag = tags[a];
var elems = document.body.getElementsByTagName(tag);
for (b = 0; b < elems.length; b++) {
var elem = elems[b];
var id = elem.innerText + count;
var id = id.replace(/\s/g,'').replace('?','').toLowerCase();
var theurl = url+"#"+id;
var link = 'javascript:var d=document;var a=d.createElement(\"textarea\");a.value=\"'+theurl+'\";d.body.appendChild(a);a.select();d.execCommand(\"copy\");d.body.removeChild(a);alert(\"Link Copied To Clipboard\");';
var headinglink = "<a class='headinglink' title='Copy To Clipboard' onclick='"+link+"'><i class='fa fa-link' aria-hidden='true'></i></a> ";
elem.innerHTML = elem.innerHTML+headinglink;
elem.id = id;
document.addEventListener("DOMContentLoaded", function(){

I am using fontawesome for my icon, you may want to replace it with text (eg "Copy") or add an image in instead. You would want to replace the following code with your code:

<i class='fa fa-link' aria-hidden='true'></i>

Related readings:
Hash Tag Links That Don’t Headbutt The Browser Window

Automatically add IDs to your headings (WordPress & PHP)

Notify of
Inline Feedbacks
View all comments

Related Reading

JavaScript Generated Anchor Link Menu From Heading Tags

Read More

YouTube Autoplay and Full Height Background Videos 2020

Read More

Turning Divi Toggles in FAQ Schema for Google FAQ rich results with Javascript + JSON

Read More

Would love your thoughts, please comment.x