Automatically add anchors to block content

I’m working on a site at the moment that will possibly become Pulse powered. Although I’m adding the site content for the client I can see they will be adding new pages and blocks of content as the site grows. To aid deep linking from one part of the site to another I’m currently manually adding anchors to headings within blocks like this;
<h2 id="my-heading">My heading</h2>
or
<h2><a name="my-heading"></a>My heading</h2>

I can then link from another page directly to this section with;
<a href="my-page#my-heading">go to my heading</a>

Unfortunately I can’t see my client getting then hang of adding these anchors into the block content.

I just created the following vanilla JavaScript that will add the anchors when the page loads and it appears to work before the browser jumps to the newly created anchor on the page. So far, so good.

<script> function makeanchors(what,where){ var target = document.getElementsByTagName(where); if (target[0]){ var allwhats = target[0].getElementsByTagName(what); for (var i=0; i < allwhats.length; i++){ var headingtext = allwhats[i].innerHTML; var thisID = convert_to_id(headingtext); if (!allwhats[i].id){ allwhats[i].id = thisID; } else { allwhats[i].innerHTML = '<a name="'+ thisID +'"></a>'+ headingtext; } } } } function convert_to_id(text){ return text .toLowerCase() .replace(/ /g,'-') .replace(/[^\w-]+/g,'') ; } makeanchors("h2","body"); </script>

Can any of you clever people think of a way to do this in Redactor once before the block content is saved rather than have to do it each time the page loads?

Please consider this a feature request. :slight_smile:

1 Like

This topic was automatically closed after 5 hours. New replies are no longer allowed.