jQuery Text Scale to Element Size Script


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

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


Copy this code and paste it in your HTML
  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. });

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

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.