Dive Into Greasemonkey

Teaching an old web new tricks

5.3. Case study: Ain't It Readable

Overriding page styles

Ain't It Cool News is a site devoted to entertainment news. The site is wonderful; I highly recommend it. Unfortunately, I can't stand how the site looks. Every headline is too large, too bold, and changes color as you move your cursor over it. So I wrote a user script that changes the styles I don't like.

Example: aintitreadable.user.js

// ==UserScript==
// @name          Ain't It Readable
// @namespace     http://diveintogreasemonkey.org/download/
// @description   change style on aint-it-cool-news.com
// @include       http://aint-it-cool-news.com/*
// @include       http://*.aint-it-cool-news.com/*
// ==/UserScript==

function addGlobalStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}

addGlobalStyle(
'h1, h2, h3, h4 {' +
'  font-size: 12px ! important;' +
'  line-height: 14px ! important;' +
'  font-weight: normal ! important;' +
'}' +
'h1:hover, h2:hover, h3:hover, h4:hover {' +
'  background-color: inherit ! important;' +
'  color: inherit ! important;' +
'}');

This user script is very simple. First I define a function which adds arbitrary CSS styles to the page. See Adding CSS styles for more information about this function.

function addGlobalStyle(css) {
    var head, style;
    head = document.getElementsByTagName('head')[0];
    if (!head) { return; }
    style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = css;
    head.appendChild(style);
}

Then I simply call the function with the CSS styles I want to add: make the headlines smaller and not bold, and remove the color change when you move the cursor over them. In this case, the page defines style rules for each of these, so I use the ! important keyword to make sure that my style rules are applied instead of the page's original rules.

Note that the function takes only one argument, a string that contains all the style rules to add. I've formatted the string for readability here, but it's still just a string.

addGlobalStyle(
'h1, h2, h3, h4 {' +
'  font-size: 12px ! important;' +
'  line-height: 14px ! important;' +
'  font-weight: normal ! important;' +
'}' +
'h1:hover, h2:hover, h3:hover, h4:hover {' +
'  background-color: inherit ! important;' +
'  color: inherit ! important;' +
'}');
← Case study: Bloglines Autoload
Case study: Offsite Blank →