Sunday, April 24, 2005

Blogspot hack: random quotes in sub-header

I wanted to put random quotes instead of the same old blog description. Here's how I did it.

Classic Blogger

Find the $BlogDescription$ tag in your template and replace with the sample code below.

Blogger Beta

While in Edit HTML, click on the Expand Widget Templates checkbox, then look for <data:description/> where you will replace this tag by the sample code below. Don't forget to replace $BlogDescription$ by <data:description/>.

Sample code


<p id="description">
<script language="javascript">
var asText=new Array(
'quote1:simple text',
'quote2:<i>embeded HTML</i>',
'quote3:<A href="http://somelink.com/"
target="_new">with hyperlink</A>'
);
document.write(
asText[
Math.round(Math.random()*(asText.length-1))
]
);
</script>
<noscript><$BlogDescription$></noscript></p>

How does it work?

  • We want to keep the same formating for the sub-header (the blog description), so we keep the <p id="description"> tag.
  • the JavaScript asText array can be as short or contain as many entries as you want, as long as you take care of enclosing each one in single quotes, and separate them with commas (excet the last one). You can embed HTML syntax within the text to alter its display (quote2), and even links (quote3).
  • Once the array is defined, the last thing to do is simply to write one of the quotes randomly. Lets look at this closer:
    1. Math.random() generates a random number between 0 and 1.
    2. When multipled by the number of entries in our array (asText.length-1), we get a random number between 0 and the number of entries in the array (we substract 1 because the first position of an array, in JavaScript, is 0, not 1).
    3. asText[n] provides the text of the element n of the array
    4. Finally, document.write is the JavaScript function used to output the text.
  • We keep the original $BlogDescription$ within <noscript> so crawlers (like Google), will see your original text and take it into account in search results (you could also remove the <noscript> tags if you still want to show your original Blogger description).
See my other Blogger hacks:
Post a Comment