EDIT: Ok, so I approached the problem the wrong way: to do what I intended to, I just needed to check if there was an overflow.
Here is the code (if it can help anyone):
<script type="text/javascript">
function textfit(){
var spans = document.body.getElementsByTagName("span");
for(var i = 0, l = spans.length; i < l; i++){
var span = spans[i];
var font = window.getComputedStyle(span, null).getPropertyValue('font-size');
var fontSize = parseInt(font);
do {
span.style.fontSize = (fontSize --) + "px";
} while (span.scrollHeight > span.clientHeight || span.scrollWidth > span.clientWidth);
}
}
$(document).ready(function() {
textfit();
});
</script>
OLD POST:
My problem is simple: I have a HTML page with a lot of span but not all of them have the same content. Regarding that, I want to adapt the fontsize of each content to fit perfectly its span; please note that I don't want to cut the textcontent, or add dots if it's too long, I just want to modify the fontSize.
JS:
function = textfit(){
var spans = document.body.getElementsByTagName("span");
for(var i = 0, l = spans.length; i < l; i++){
var maxHeight = spans[i].offsetHeight;
var maxWidth = spans[i].offsetWidth;
var textHeight = $(spans[i].textContent).height();
var textWidth = $(spans[i].textContent).width();
var fontSize = spans[i].style.fontSize;
do {
fontSize = fontSize - 1;
} while (textHeight > maxHeight || textWidth > maxWidth);
}
}
$(document).ready(function() {
textfit();
});
HTML/CSS:
<style>
span{
display: inline-block;
width: 100px;
height: 100px;
font-size: 20pt;
}
</style>
......
<body>
<div>
<span>SMALL</span>
<span>MEEEEEEEEEEEEEDIUM</span>
<span>HUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUGE</span>
</div>
</body>
As you may see, I'm using a "for" to run through every span and a "do...while" to adjust the font size of each of them.
My problems:
- it looks like I'm not able to get the textcontent size (getting a "null" instead)
- same thing with the fontsize (I'm getting an empty string)
Or maybe I'm approaching the problem the wrong way and I need to do it differently...
NB: JS are a little bit "new" for me so sorry if I did rookie mistakes