Skip to content

Instantly share code, notes, and snippets.

@blakehaswell
Created August 21, 2012 04:17

Revisions

  1. blakehaswell created this gist Aug 21, 2012.
    76 changes: 76 additions & 0 deletions shrink-wrap-text.jquery.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,76 @@
    (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));