Search code examples
javascriptcsssquarespace

Squarespace - Change CSS elements depending on blog tag


Hi I am not a Javascript developer and I am wondering if anyone might be able to help craft a script that changes the color of a CSS class depending on the assigned blog tag for my Squarespace site. Essentially I have three main blog categories with many sub-topics that are referenced throughout the site with specific colors. I would like to change the blog title color to match when assigning the tag.

Thanks for any help in advance!


Solution

  • Unfortunately, with Squarespace 7.1, the class attribute of blog item body elements no longer contain classes for the tags and categories assigned to the post. Furthermore, although there are similar classes located on the page, Squarespace fails to "slugify" the category and tag names, which generates invalid classes. I've reported this bug to Squarespace, but there's no telling if they'll ever address it.

    In order to work around these two issues, the following can be added via sitewide FOOTER code injection:

    <!-- Add first category class of blog item to body element for targeting blog titles via CSS. -->
    <script>
    (function() {
      var catEl = document.querySelector(".collection-5fa562b2aa23eb3d7f314914 .blog-item-category");
      var cat;
    
      if (!catEl) {
        return;
      }
    
      cat = catEl.className.match(/blog-item-category--\S*/)[0];
      if (cat) {
        document.body.classList.add(cat);
      }
    })();
    </script>
    

    With that script added, you can then add CSS via the CSS Editor like so:

    .blog-item-category--exploration .blog-item-title h1 {
      color: #f6972e !important;
    }
    

    You could repeat the above rule for each of your categories.

    Note that, because of the bug I mentioned earlier, each class will only contain the first word (all lowercase) of the tag, following the .blog-item-category-- part.