Get category color to use in CSS


(Krischan) #1

Hi there, I really like the color coding for the categories on /categories, but these colors are only sparsely used on the category page itself. Is there a way to retrieve the color of the active category to use in css? I would like to give each category a more distinctive look. Thanks!


(Simon Cossar) #2

The border colors are created with inline styles. You can get them with javascript. If you add this as a custom style to the </head> section of admin>customize>css/html it will reopen the DiscoveryCategorysView and define or redefine its didInsertElement method.

<script>
    Discourse.DiscoveryCategorysView.reopen({
        didInsertElement: function() {
            var $categories = $('.category');
            this._super(); // Calls the didInsertElement method from the super class
            
            $categories.each(function() {
                var categoryColor = $(this).css('border-color');
                // Do something with the category color
                $(this).css('color', categoryColor);
            });
        }
    });
</script>

(Krischan) #3

That’s great! Thanks so much.


(Krischan) #4

Sorry, I have another question: If I’d like to use the color in the class .topic-list>tbody>tr:first-of-type for border-top, how would I need to change this code?


(Simon Cossar) #5

This should work:

<script>
    Discourse.DiscoveryTopicsView.reopen({
        didInsertElement: function() {
            var $firstTopic = $('.topic-list > tbody > tr:first-of-type ');
            var firstTopicColor = $firstTopic.find('.badge-category-bg').css('background-color');
            
            this._super();
            
            $firstTopic.css('border-top-color', firstTopicColor);
        }
    });
</script>