Search code examples
javascriptcssfontsgreasemonkeytampermonkey

How can my script change a Specific Font (for a specific class)?


I'm trying to make my own Tampermonkey script to change a specific font style on a specific site from a cursive style to a sans-serif style.

The HTML from the site is:

<div class="text">Ask more leading questions</div>

This is nested within 2 ids and one other class.

The script I'm working on is based off of a few examples I've attempted to follow:

// ==UserScript==
// @name       Change annoying fonts
// @namespace  http://use.i.E.your.homepage/
// @version    0.1
// @description  change annoying FaracoHandRegular font to a more readable one
// @match      https://apps.bloomboard.com/*
// @copyright  2012+, You
// ==/UserScript==

function addCss(cssString) { 
var head = document.getElementsByClassName('text')[0]; 
var newCss = document.createElement('style');
newCss.type = "text/css"; 
newCss.innerHTML = cssString; 
head.appendChild(newCss); 
} 

addCss ( 
'* { font-family: Helvetica, sans-serif ! important; }' 
);


But it doesn't work.

I have never made my own scripts for either Greasemonkey or Tampermonkey before. How do I change this font?


Solution

  • Several things:

    1. First and foremost, for simple CSS changes use Stylus. It's faster and simpler.

      In this case, the equivalent Stylus script would be:

      @namespace url(http://www.w3.org/1999/xhtml);
      
      @-moz-document domain("apps.bloomboard.com") {
          .text {
              font-family: Helvetica, sans-serif !important;
          }
      }
      

      or possibly:

      @namespace url(http://www.w3.org/1999/xhtml);
      
      @-moz-document domain("apps.bloomboard.com") {
          * {
              font-family: Helvetica, sans-serif !important;
          }
      }
      

      although setting a universal style with * should be done sparingly.


    2. Don't reinvent the wheel. Most userscript engines support GM_addStyle(). Use that. Your script would become:

      // ==UserScript==
      // @name       Change annoying fonts
      // @namespace  http://use.i.E.your.homepage/
      // @version    0.1
      // @description  change annoying FaracoHandRegular font to a more readable one
      // @match      https://apps.bloomboard.com/*
      // @copyright  2012+, You
      // @grant      GM_addStyle
      // ==/UserScript==
      
      GM_addStyle ( `
          .text {
              font-family:    Helvetica, sans-serif !important;
          }
      ` );
      


    3. See and read also:

      1. About CSS
      2. Understanding Style Precedence in CSS: Specificity, Inheritance, and the Cascade
      3. About CSS selectors