Reputation: 803
I am attempting to loop through some span's of text and resize the text to fit within its containing div based on the smallest font size required to do so.
<div id="preview">
<div id="test">
<section class="slide">
<span>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<br />
Nam in mauris a magna elementum ornare vel at velit.<br />
Nulla facilisi.<br />
Sed eu odio id urna fermentum imperdiet eget sit amet enim.</span>
</section>
<section class="slide">
<span>Cras cursus ante et tortor placerat sodales.<br />
Curabitur libero quam, cursus sit amet feugiat id, elementum at lectus.<br />
Integer volutpat aliquet massa at adipiscing.<br />
Vivamus purus leo</span>
</section>
</div><!--/ #test -->
</div><!--/ #preview -->
My jquery I have to do this so far is
var fontSizeArray = [];
$('#test > .slide').children('span').each(function () {
var currentFontSize = parseInt($(this).css('font-size'));
do {
currentFontSize = currentFontSize + 1;
$(this).css('font-size', currentFontSize);
} while ($(this).width() < $('#test').width());
fontSizeArray.push(currentFontSize);
});
var smallest = Math.min.apply( null, fontSizeArray );
$('#test > .slide').children('span').each(function () {
$(this).css('font-size', smallest);
});
I have created a fiddle to better illustrate this.
Basically all of the text should be resized to fit within the div #test
Upvotes: 1
Views: 201
Reputation: 191749
Add a conditional after the loop that checks if you've gone too far:
if ($(this).width() > $("#test").width()) {
currentFontSize--;
}
Upvotes: 2