Skip to content

Customizing visited links

I was considering adding some “special styling” to visited links, like this:

…when I remembered :visited links cannot use all CSS properties, just a few:

(source: MDN)

So I was searching and found this cool article that describes a technique that you can use to store in localstorage visited links, and then style as you want. This only applies to links visited after you implement the strategy, unfortunately.

But here’s an implementation - credits: using that article strategy - which I tried but then haven’t committed, so writing to not forget.

You save to local storage when someone visits a page:

<script>
  localStorage.setItem(
    'visited-' + window.location.pathname,
    true
  )
</script>

Once the page that hosts the links loads (which might be different, for example a homepage or a blog posts list page), you add data-visited=true to all links visited:

<script>
  window.addEventListener(
    'DOMContentLoaded',
    () => {
      const links =
        document.getElementsByTagName('a')
      for (let i = 0; i < links.length; i++) {
        var link = links[i]
        if (
          link.host == window.location.host &&
          localStorage.getItem(
            'visited-' + link.pathname
          )
        ) {
          link.dataset.visited = true
        }
      }
    }
  )
</script>

Now you can style with any CSS property:

a[data-visited] {
  border-bottom: 1px dashed rgb(250, 204, 21);
}
a[data-visited]:after {
  content: ' ✔︎';
}

→ Get my CSS Handbook

download all my books for free

  • javascript handbook
  • typescript handbook
  • css handbook
  • node.js handbook
  • astro handbook
  • html handbook
  • next.js pages router handbook
  • alpine.js handbook
  • htmx handbook
  • react handbook
  • sql handbook
  • git cheat sheet
  • laravel handbook
  • express handbook
  • swift handbook
  • go handbook
  • php handbook
  • python handbook
  • cli handbook
  • c handbook

subscribe to my newsletter to get them

Terms: by subscribing to the newsletter you agree the following terms and conditions and privacy policy. The aim of the newsletter is to keep you up to date about new tutorials, new book releases or courses organized by Flavio. If you wish to unsubscribe from the newsletter, you can click the unsubscribe link that's present at the bottom of each email, anytime. I will not communicate/spread/publish or otherwise give away your address. Your email address is the only personal information collected, and it's only collected for the primary purpose of keeping you informed through the newsletter. It's stored in a secure server based in the EU. You can contact Flavio by emailing [email protected]. These terms and conditions are governed by the laws in force in Italy and you unconditionally submit to the jurisdiction of the courts of Italy.

Related posts about css: