Scroll to top

Jan 25, 2021

The home on the web of Colin Walker.
Find out more on /about, say /EHLO, or tune in to the daily RSS feed.

Jan 25, 2021#p3

One thing I'd looked at adding (but was desperately trying to over-engineer) was support for fragmentions: linking to and highlighting specific sections of a page.

I remembered that I had written my own script in place of the WordPress plugin originally being used so repurposed this with a bit of an update:

function fragmention() {
  var loc = location.href;
  var locIndex = loc.indexOf("##");

  if (locIndex != -1) {
    var hash = loc.substring(locIndex+2).toLowerCase();
  }

  while (hash.indexOf('+') != -1) {
    hash = hash.replace("+", " ");
  }

  var pTags = document.getElementsByTagName("p");

  for (var p=0; p<pTags.length; p++) {
    var pContent = pTags[p].innerHTML.toLowerCase();

    if (pContent.indexOf(hash) != -1) {
      pTags[p].setAttribute("fragmention", "");
      pTags[p].scrollIntoView();
      break;
    }
  }
}