Skip to content

Instantly share code, notes, and snippets.

@jbuncle
Last active May 19, 2016 10:47
Show Gist options
  • Save jbuncle/317a3b07bd00896f618fe02c7839e92d to your computer and use it in GitHub Desktop.
Save jbuncle/317a3b07bd00896f618fe02c7839e92d to your computer and use it in GitHub Desktop.
jQuery Plugin for responsively scaling text to fill it's parent width.
/*!
* jQuery Plugin for responsively scaling text to fill it's parent width.
*
* Copyright 2016 James Buncle
*
* Released under the MIT license.
* http://jquery.org/license
*
*/
(function ($) {
$.fn.scaleText = function (options) {
var defaults = {
increment: 5,
maxwidth: 'auto',
minwidth: 0
};
var settings = $.extend(defaults, options);
return this.each(function () {
var $this = $(this);
$(window).resize(function () {
scaleText($this, settings);
});
scaleText($this, settings);
});
};
function scaleText($obj, settings) {
var targetWidth = $obj.parent().width();
if (settings.maxwidth !== 'auto') {
if (targetWidth > settings.maxwidth) {
targetWidth = settings.maxwidth;
}
}
if (targetWidth < settings.minwidth) {
targetWidth = settings.minwidth;
}
targetWidth = parseFloat(targetWidth);
var initialFontSize = parseFloat(2.5);
//Calculate scale factor
$obj.css({
'font-size': initialFontSize + 'px',
'width': 'auto',
'display': 'inline',
'position': 'relative'
});
var currentWidth = parseFloat($obj.width());
var scale = targetWidth / currentWidth;
var newFontSize = Math.floor((initialFontSize) * scale);
$obj.css({
'font-size': newFontSize,
'display': '',
'position': ''
});
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment