Posted By

Narthur on 11/01/11


Tagged

javascript jquery text size scale


Versions (?)

jQuery Text Scale to Element Size Script


 / Published in: jQuery
 

URL: http://jsfiddle.net/mfJPm/5/

jQuery to set the width of some text to the width of a given element.

  1. $.fn.boxWidth = function(){
  2. var sensor = $('<div />').css({margin: 0, padding: 0});
  3. $(this).append(sensor);
  4. var width = sensor.width();
  5. sensor.remove();
  6. return width;
  7. };
  8.  
  9. $.fn.textWidth = function(){
  10. var html_org = $(this).html();
  11. var html_calc = '<span>' + html_org + '</span>'
  12. $(this).html(html_calc);
  13. var width = $(this).find('span:first').width();
  14. $(this).html(html_org);
  15. return width;
  16. };
  17.  
  18. function scaleText(textTarget, widthTarget) {
  19. var textWidth = textTarget.textWidth();
  20. var boxWidth = widthTarget.boxWidth();
  21. var fontSize = .1;
  22. while (textWidth > boxWidth) {
  23. fontSize -= .1;
  24. textTarget.css('font-size', fontSize + 'em');
  25. textWidth = textTarget.textWidth();
  26. boxWidth = widthTarget.boxWidth();
  27. }
  28. while (textWidth < boxWidth) {
  29. fontSize += .1;
  30. textTarget.css('font-size', fontSize + 'em');
  31. textWidth = textTarget.textWidth();
  32. boxWidth = widthTarget.boxWidth();
  33. }
  34. }
  35.  
  36. var textTarget = $('p'); // replace with the element containing the text you want to resize
  37. var widthTarget = $('p'); // replace with the element whose width you want to match
  38.  
  39. $('document').ready(function() {
  40. scaleText(textTarget, widthTarget);
  41. });
  42.  
  43. $(window).resize(function() {
  44. scaleText(textTarget, widthTarget);
  45. });

Report this snippet  

You need to login to post a comment.