Revision: 52748
Initial Code
Initial URL
Initial Description
Initial Title
Initial Tags
Initial Language
at November 1, 2011 09:37 by Narthur
Initial Code
$.fn.boxWidth = function(){ var sensor = $('<div />').css({margin: 0, padding: 0}); $(this).append(sensor); var width = sensor.width(); sensor.remove(); return width; }; $.fn.textWidth = function(){ var html_org = $(this).html(); var html_calc = '<span>' + html_org + '</span>' $(this).html(html_calc); var width = $(this).find('span:first').width(); $(this).html(html_org); return width; }; function scaleText(textTarget, widthTarget) { var textWidth = textTarget.textWidth(); var boxWidth = widthTarget.boxWidth(); var fontSize = .1; while (textWidth > boxWidth) { fontSize -= .1; textTarget.css('font-size', fontSize + 'em'); textWidth = textTarget.textWidth(); boxWidth = widthTarget.boxWidth(); } while (textWidth < boxWidth) { fontSize += .1; textTarget.css('font-size', fontSize + 'em'); textWidth = textTarget.textWidth(); boxWidth = widthTarget.boxWidth(); } } var textTarget = $('p'); // replace with the element containing the text you want to resize var widthTarget = $('p'); // replace with the element whose width you want to match $('document').ready(function() { scaleText(textTarget, widthTarget); }); $(window).resize(function() { scaleText(textTarget, widthTarget); });
Initial URL
http://jsfiddle.net/mfJPm/5/
Initial Description
jQuery to set the width of some text to the width of a given element.
Initial Title
jQuery Text Scale to Element Size Script
Initial Tags
javascript, jquery, text
Initial Language
jQuery