"Count" blogger posts on page

In some scripts it is be useful to know the number of posts on a page. It can be used for example to hide the "previous posts" link, I'll write about that some time later. Information about posts and their count is available only in the blog posts widget which shows the posts. First I made javascript function which incremented a counter on each post loop iteration to get the post count, but then I found out that posts widget has a template variable called data:numPosts (not documented), which holds the number of posts displayed on current page. So the code got much simpler, and that's why quotation marks for "count". Here is how you do it.



Declare javascript variable numPosts



This step is not absolutely necessary, but I like to declare the variables used in the whole page. Best place for this is in html head. So, edit template html, find </head> and add this before it:

<script type='text/javascript'>
var numPosts = 7;
</script>  

Default value is 7 posts per page. If there is already some javascript before </head>, you can also add only the var numPosts = 7; line before the </script> tag. Something like this (highlighted line is added, others are old lines):

  // ... some old code here ...
// ... some old code here ...

var numPosts = 7;

//]]>
</script>

Assign actual numPosts value in the posts widget



Ok, for this one you need to edit the html, again, and select Expand Widget Templates. Then find line:

<b:includable id='main' var='top'>

and add after that these lines:

<script type='text/javascript'>
numPosts = <data:numPosts/>;
</script>

And now we have the number of posts showing on the page in javascript variable numPosts.



Testing



To test that code works, find </body>, and add before that:

<script type='text/javascript'>
document.title = document.title + " (viewing " + numPosts + " posts)";
</script>

Again, if there is already some javascript there, before </body>, you can also add document.title... line there. Now when viewing the blog, window title should be "YourBlogName (viewing # posts), where # is the number of posts on page.