Jump to content

Snippets/Style pages based on categories

From mediawiki.org
How to use Snippets
List of Snippets
Style pages based on categories
Language(s): JavaScript
Compatible with: MediaWiki 1.17+ 

Description

[edit]

Adds a CSS class to the <body> tag for every category the current page belongs to. This can be useful to apply specific styles to all pages on the wiki that are included on a given category. Each class will have a "cat-" prefix followed by the category name, with spaces and dots converted to underscores and special characters encoded.

You can later write styles like body.cat-Some_category to apply styles to pages belonging to that category.

Code

[edit]
/**
 * Adds CSS classes to the body tag based on the categories this page belongs to
 *
 * @source https://www.mediawiki.org/wiki/Snippets/Style_pages_based_on_categories
 * @revision 2016-01-18
 */
(function($, mw) {
  var fn = function() {
    var cats = mw.config.get('wgCategories'), newClasses;
    if (cats) {
      newClasses = $.map(cats, function(el) {
        return 'cat-' + encodeURIComponent(el.replace(/[ .]/g, '_')).replace(/%/g, '_');
      }).join(' ');
      $(document.body).addClass(newClasses);
    }
  };
  if (document.body) {
    fn();
  } else {
    $(fn);
  }
})(jQuery, mw);

See also

[edit]