Linkable headings

Hi all!

I’m trying to get a bunch of technical articles published on a Wix-powered website. To reference the content of these articles in our reviews and to give feedback to our community, it’s crucial that we can link to specific sections of the articles. And I don’t mean create a link from one Wix page to another Wix page, I mean anyone viewing the site should be able to pick any heading and copy a nice human readable link to that heading.

I’ve written a bit of CSS and JS that does exactly what I want, and it works great when manually run from the browser developer console.

  /* Header anchor links */
  /* Based on https://jhirth.github.io/2017-01-15/quick-and-easy-header-fragment-links-for-jekyll-powered-sites */
  .linkableHeader {
    position: relative;
  }
  .linkableHeader > a {
    display: none;
    color: #0c77be;
    
    position: absolute;
    padding-left: 0.2em;
    top: 0;
    left: -1em;
    /* Ensure there's no gap allowing the link to disappear when trying to reach it */
    min-width: 1em;
  }
  .linkableHeader:hover > a {
    display: block;
  }
function getText(element){
  let children = element.childNodes;
  if (children.length > 1) console.log("Found more than 1 child in element")
  if (children[0].nodeType == 3) { // 3 = text node
    return children[0].nodeValue;
  } else {
    return getText(children[0]);
  }
}

function makeLinkableHeaders(element) {
  // Skipping h1 as it represents the whole page and is redundant to have
  // an anchor link to
  for(let h of element.querySelectorAll('h2[id], h3[id], h4[id], h5[id], h6[id]')) {
    // Wix adds a bunch of nested junk elements. Dive to the textNode to get the
    // actual text content.
    let title = getText(h);
    // Wix gives the elements random junk IDs. Change header ID to something based
    // on its text content, so anchor links are human readable.
    let anchor = title.replaceAll(' ', '-').toLowerCase();
    console.log(anchor);
    h.id = anchor;
    
    // Add the link
    h.innerHTML += `<a href="#${anchor}" aria-hidden="true">#</a>`;
    h.classList.add('linkableHeader');
  }
}

let article = document.getElementsByClassName('wixui-rich-content-viewer')[0];
makeLinkableHeaders(article);

This is the result:

Hovering a heading gives you little link in the margin

Clicking the link scrolls to it, and copying the address from the address bar gives you a sharable link to that specific heading.

The problem I’m facing is that Wix doesn’t seem to allow any DOM access. Everything is locked in and sandboxed away.

Any other way to do this?

Is it possible to log a feature request somewhere to get this built into Wix itself? Other more conventional services like GitHub supports this natively.

1 Like