jquery automatic text resize


/ Published in: jQuery
Save to your folder(s)

simple jquery plugin that powers the text auto-resizing that is the basis of textagon.com


Copy this code and paste it in your HTML
  1. function resizer() {
  2. this.resize = function(element, size) {
  3. this.init(element);
  4. element.css('font-size', this.growTo(size) + 'px');
  5. this.tester.remove();
  6. }
  7.  
  8. this.init = function(element) {
  9. $('#resizeroo').remove();
  10. this.tester = element.clone();
  11. this.tester.css('display', 'none');
  12. this.tester.css('position', 'absolute');
  13. this.tester.css('height', 'auto');
  14. this.tester.css('width', 'auto');
  15. $('body').append(this.tester);
  16. this.size = 1;
  17. this.tester.css('font-size', this.size + 'px');
  18. }
  19.  
  20. this.emitWidth = function() {
  21. console.log(this.tester.width());
  22. }
  23.  
  24. this.grow = function() {
  25. this.size++;
  26. this.setSize();
  27. }
  28.  
  29. this.setSize = function(size) {
  30. this.size = size;
  31. this.tester.css('font-size', this.size + 'px');
  32. }
  33.  
  34. this.growTo = function(limit) {
  35. lower = 1;
  36. upper = limit-1;
  37.  
  38. // do binary search going midway to determine
  39. // the best size
  40. while( lower < upper ) {
  41. midpoint = Math.ceil((upper+lower)/2);
  42. this.setSize(midpoint);
  43.  
  44. if( Math.abs(limit - this.tester.width()) <= 1) {
  45. // close enough
  46. break
  47. }
  48.  
  49. if(this.tester.width() >= limit) {
  50. upper = this.size-1;
  51. }
  52. else {
  53. lower = this.size+1;
  54. }
  55. }
  56.  
  57. while(this.tester.width() > limit) {
  58. this.setSize(this.size-1);
  59. }
  60.  
  61. return(this.size);
  62.  
  63. }
  64. }
  65.  
  66.  
  67. (function( $ ){
  68. $.fn.widtherize = function( options ) {
  69. return this.each(function() {
  70. var settings = {
  71. 'width' : 500
  72. };
  73. if ( options ) {
  74. $.extend( settings, options );
  75. }
  76. r = new resizer();
  77. r.resize($(this), settings.width);
  78. });
  79. };
  80. })( jQuery );

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.