April 13, 2020

Dynamically Adding “Link To Section” to Heading Tags with Javascript

I often want to link to a part of a blog post that is half way down the page. Makes for smart content sharing and linking as sometimes a blog post may be 3000+ words long and you cant 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.


<script>
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++) {
count++;
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(){
headingLinks();
});
</script>

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>
Was this helpful?
YesNo
Category: Code

Author

“surfing the web and the waves”. - With a degree in Information Technology (majoring in Networking), a Cert IV in Small Business Management, and having been interested in website design and development since 2010 (With an interest in computers since about age 10) – Ryan has the skills, experience and knowledge with building websites, improving SEO and running online ads.