Blogger: writing proper plurals with CSS 2

Looking for something very unrelated, I stumbled upon an article on how to tweak blogger pages to render proper plurals for comments (0 comments, 1 comment, 2 comments, ...). It was a particularly smelly javascript solution, in that it wouldn't write anything at all for javascript disabled browsers. Poor style.

And while doing anything like this client side is kind of sad, I got this sudden silly urge of doing it right, and came up with a CSS 2 selectors solution in the spirit of, well, I don't know what. Just mark any place with a plural in it with a <span class="plural" name="<$BlogItemCommentCount$>"><$BlogItemCommentCount$> comment</span> tag (<$BlogItemCommentCount$> being the server-side generated number you want to act on to find plurals) and tuck in this bit of CSS in your stylesheet somewhere:

.plural[name]:after    { content:"s"; }
.plural[name="1"]:after { content:""; }

and behold! :-) I use the same trick to tag my user scripts with a little GreaseMonkeyGreaseMonkey icon, by the way, so I just have to type <a class="userscript" href="....user.js"> whenever I tuck in a link to some new user script I've conjured up. Comfy.

But back to plurals. Downside? Internet Explorer (at least up to present day) doesn't grok CSS 2 selectors. So to get it working in at least as many (and probably more) browsers, we get to add a bit of javascript to post-process the page if needed:

<script type="text/javascript"><!--
// in case your browser is crummy and doesn't grok CSS 2 selectors:
function fixPlural()
var ua = navigator.userAgent, plurals, i, node;
// tweak <span class="plural" name="N">N Comment</span> blocks?
if( /MSIE [0-6]/.test( ua ) && !/compatible/i.test( ua ) )
plurals = document.getElementsByTagName( 'span' );
for( i=0; i<plurals.length; i++ )
if( /plural/.test( (node=plurals[i]).className ) && node.name != 1 )
node.innerHTML += 's';
// and just in case this browser does support CSS2, toss the class
node.className = node.className.replace( /plural/, '' );

and then find your <body> tag and rewrite it to <body onload="fixPlural();">. Congratulations on your human readable blog! :-)
blog comments powered by Disqus