Skip to content

Instantly share code, notes, and snippets.

@mojowen
Created June 14, 2012 18:12
Show Gist options
  • Save mojowen/2931897 to your computer and use it in GitHub Desktop.
Save mojowen/2931897 to your computer and use it in GitHub Desktop.
jQuery plugin for making a div into a thermometer
(function($){
$.fn.thermometer = function(fill,total,thing) {
function addCommas(nStr) { // from http://www.mredkj.com/javascript/numberFormat.html
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) x1 = x1.replace(rgx, '$1' + ',' + '$2');
return x1 + x2;
}
var fill = parseInt(fill),
total = parseInt(total),
percent = fill / total,
height = this.height(),
marginTop = 'margin-top:'+( height * (1-percent) )+'px',
height = percent*100+'%',
fillDiv = document.createElement('div'),
textTotal = document.createElement('div'),
textToGo = document.createElement('div'),
thing = typeof thing != 'undefined' ? ' '+thing : '',
innerDiv = document.createElement('div')
fillDiv.style.cssText = ['height:'+height,marginTop,'width:100%'].join(';')
textToGo.style.cssText = ['margin-top:-'+height,'width:100%','margin-bottom: 0','text-align: center','float:left'].join(';')
textTotal.style.cssText = ['width:100%','margin: 0','text-align: center','float:left','margin-top: -1.4em'].join(';')
innerDiv.style.cssText = ['overflow: hidden','height: 100%','width:100%','border: 2px solid','border-radius: 15px'].join(';')
textToGo.textContent = 'Only '+addCommas(total-fill)+thing+' to go'
textTotal.textContent = addCommas(total)
fillDiv.className = "fill"
textTotal.className = "label total"
textToGo.className = "label to-go"
innerDiv.className = 'inner'
innerDiv.appendChild(fillDiv)
innerDiv.appendChild(textToGo)
this[0].appendChild(textTotal)
this[0].appendChild(innerDiv)
}
})(jQuery);
@mojowen
Copy link
Author

mojowen commented Jun 14, 2012

Quick jQuery plugin that's useful for making a thermometer out of a div.

Must pass two values: fill and total and optionally thing.

  • fill is the amount it should be filled
  • total is the total
  • thing is if you want the thermometer to be labeled

The original div should be styled for position and size, the plugin should take care of the rest. Two divs with text the classes .label affixed to them

EXAMPLE

HTML: <div id="thermometer" style="width: 200px; height: 300px; float: right; margin: -366px 130px 0 0;"></div>

Javascript:
jQuery(document).ready( function($) { if( gathered && total ) $('#thermometer').thermometer(gathered, total ,'Signatures') })

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment