Vincent Cheung

Vincent Cheung's Blog


« Newer Post Home Older Post »

Friday, September 15, 2006

Random!

The picture on the top right now randomly rotates through a couple different photos, as before.

Today's new feature is the "Random Post" link at the bottom and/or top of the page, depending on where you are in the blog.

Here's a code snippet.

Put this between <head> and </head> (this loads the post urls into an array):

<b:section class='random' id='random'>
<b:widget id='BlogArchive2' locked='false' title='Blog Archive' type='BlogArchive'>
<b:includable id='main'>
  <script type='text/javascript'>
    var randPostNames = new Array();
  </script>

  <b:include data='data' name='interval'/>
</b:includable>
<b:includable id='interval' var='intervalData'>
  <b:loop values='data:intervalData' var='i'>
    <b:if cond='data:i.data'>
      <b:include data='i.data' name='interval'/>
    </b:if>
    <b:if cond='data:i.posts'>
      <script type='text/javascript'>
        <b:loop values='data:i.posts' var='j'>
          randPostNames.push('<data:j.url/>');
        </b:loop>
      </script>
    </b:if>
  </b:loop>
</b:includable>
</b:widget>
</b:section>


Then put this code any where you want the link to a random post (this randomly samples from the array of posts and creates a link):

<script type='text/javascript'>
  /*<![CDATA[*/
  var randPostIdx = Math.floor(Math.random() * randPostNames.length);
  document.write("<a href='" + randPostNames[randPostIdx] + "'>Random Post</a>");
  /*]]>*/
</script>


The one thing about the random post is that it will link only to one of the latest 50 posts because of how blogger is doing the data tags in the hierarchical archives.

1 Comment:

Tommeh said...

Hey, great tip! I've been looking for a random post button for a while that didn't require de.lic.ious

Post a Comment