Published on April 13, 2020

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

Ryan Jones

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);;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; = 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)

Add To Favorites
Notify of
Inline Feedbacks
View all comments
Would love your thoughts, please comment.x
That Website Is Me

That Website Is Me

Typically replies within an hour

I will be back soon

Contact Us

General Contact Form
That Website Is Me
Hey there 👋
How can I help you?
Start Chat with: