jQuery Reading Progress Meter

On my Amazon reading list page I wanted to add a progress bar and ahead/behind schedule counter similar to that on Goodreads. For their reading progress meter, you enter how many books you plan to read, and then your account page shows you a progress bar indicating how many books you’ve read and how far ahead or behind schedule you are as you progress through the year.

Basically, my version of this works by figuring the average number of books you should read per day, and then comparing the number of books you’ve read to date against (average books per day * current day as a numerical value).

In the following script, the “books” value is coming from the table counter. You’d need to obtain this value from somewhere, either hard-coded or in data obtained from Amazon, etc.

First, enable the jQuery UI progress bar widget in Drupal:

<?php
drupal_add_library('system', 'ui.progressbar');
?>

Add the progress bar to your page with some styling info:

<div id="progresswidget">
  <div id="progresslabel"></div>
  <div id="progressbar"></div>
</div>

Finally, we write some JavaScript to calculate and display our data:

<script>
calculateFigures();

function calculateFigures() {

    // Define books to read
    var toRead = 52;  

    // Get percentage of books read
    var compPct = books / toRead * 100;
    var compPctRounded = compPct.toFixed(0);
    
    // Determine average number of books per day
    var avgPerDay = toRead / 365;

    // Determine day numerically from beginning of year, e.g., Feb. 5 = 36
    var now = new Date();
    var start = new Date(now.getFullYear(), 0, 0);
    var diff = now - start;
    var oneDay = 1000 * 60 * 60 * 24;
    var day = Math.floor(diff / oneDay);
    
    // Determine books ahead/behind schedule
    var compWord = "";
    var onSchedule = (avgPerDay * day).toFixed(0);
    var bookDiff = books - onSchedule;
    if (bookDiff < 0) {
        compWord = "behind";
    } else {
        compWord = "ahead of";
    }

    // Print books read and ahead/behind schedule with progress bar
    jQuery(function() {
      jQuery( "#progressbar" ).progressbar({
        value: compPct
      });
      jQuery( "#progresslabel" ).text(books + " / " + toRead + " (" + compPctRounded + "%) books completed. " + Math.abs(bookDiff) + " books " + compWord + " schedule.");
    }); 
};

</script>

Remember, we use ‘jQuery’ instead of the ‘$’ shorthand here because Drupal uses jQuery’s noconflict mode. In many environments this isn’t necessary.

Loading

Leave a Reply

Your email address will not be published. Required fields are marked *