Created
August 21, 2012 04:17
-
-
Save blakehaswell/3411477 to your computer and use it in GitHub Desktop.
jQuery plugin to shrink text if the container is too small. Useful for buttons, text inputs, etc.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function (window, undefined) { | |
"use strict"; | |
var $ = window.jQuery; | |
$.fn.shrinkWrapText = function () { | |
return this.each(function () { | |
var $el = $(this); | |
var sw = new ShrinkWrapper($el); | |
sw.init(); | |
$el.data("shrinkWrapper", sw); | |
}); | |
}; | |
var ShrinkWrapper = function ($el) { | |
this.$el = $el; | |
this.css = { | |
fontFamily: this.$el.css("font-family"), | |
fontSize: this.$el.css("font-size"), | |
fontStyle: this.$el.css("font-style"), | |
fontWeight: this.$el.css("font-weight"), | |
letterSpacing: this.$el.css("letter-spacing"), | |
textTransform: this.$el.css("text-transform"), | |
wordSpacing: this.$el.css("word-spacing") | |
}; | |
}; | |
ShrinkWrapper.fn = ShrinkWrapper.prototype; | |
ShrinkWrapper.fn.init = function () { | |
$(window).on("load resize", $.proxy(this.updateFontSize, this)); | |
this.$el.on("keyup", $.proxy(this.updateFontSize, this)); | |
}; | |
ShrinkWrapper.fn.updateFontSize = function () { | |
var fontSize = this.getMaxFontSize(); | |
this.$el.css("font-size", fontSize); | |
}; | |
ShrinkWrapper.fn.getMaxFontSize = function () { | |
var fontSize = parseInt(this.css.fontSize, 10); | |
var text = this.getText(); | |
if (!text) { | |
return fontSize; | |
} | |
var width = this.$el.width(); | |
var $tmp = $("<div></div>"); | |
// Ensure that the element is only as wide as the text it contains. | |
$tmp.css("display", "inline"); | |
$tmp.css(this.css); | |
$tmp.text(text); | |
$tmp.appendTo("body"); | |
while ($tmp.width() > width && fontSize >= 8) { | |
fontSize -= 1; | |
$tmp.css("font-size", fontSize); | |
} | |
$tmp.remove(); | |
return fontSize; | |
}; | |
ShrinkWrapper.fn.getText = function () { | |
return this.$el.text() || this.$el.val(); | |
}; | |
}(window)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment