Fit text in container

by joquery

HTML

<div class="single">
    Das ist der lange Text.
</div>

<div class="multi">
    Das ist der lange Text. Er ist zu lang.
</div>

CSS

div {
    width: 100px;
    height: 50px;
    background-color: #eaeaea;
    margin: 0 0 20px 0;
    font-size: 16px;
    font-family: Calibri, sans-serif;
    overflow: hidden;
}

div span {
    margin:0;
    padding:0;
}

.single {
    white-space:nowrap;
    height: 20px;
}

JavaScript

fitText($("div.single"),"single");
fitText($("div.multi"), "multi");

function fitText($container, type) {
    
    var text = $container.text();
    var oldFontSize = parseInt($container.css("font-size"));
    $container.empty();
    var $tester = $('<span/>').text(text).appendTo($container);
    
    var newFontSize = oldFontSize;
    
    switch (type) {
        case "single":
            var containerWidth = $container.width(); // const
            
            do {
                // decrease font-size prop
                newFontSize -= 1;
                $tester.css("font-size", newFontSize + "px");
                
            } while ($tester.width() > containerWidth);
            
            break;
        case "multi":
            var containerHeight = $container.height(); // const
            
            do {
                // decrease font-size prop
                newFontSize -= 1;
                $tester.css("font-size", newFontSize + "px");
                                
            } while ($tester.height() > containerHeight);
            
            break;
    }
    
    $tester.remove();
    $container.css("font-size", newFontSize).text(text);
    
    
};