As I embark on the journey to expand my coding skills, I have decided to challenge myself by tackling some tasks without relying on jQuery. One particular challenge that I am currently facing involves a fixed contenteditable div. The goal is to adjust the font size dynamically so that the added text fits within the div without exceeding its scrollHeight
.
In certain scenarios, such as when the text is programmatically replaced or deleted by the user, the scrollHeight
does not update accordingly. This poses a problem as the font size needs to be adjusted based on the actual content height of the div.
In the provided example, the clientHeight
is 142 and the initial scrollHeight
is 158. A loop is used to gradually reduce the font size until the scrollHeight
matches the clientHeight
. However, if a line of text is deleted, the scrollHeight
remains unchanged at 142.
Below is the code snippet used to handle the font size adjustments:
var textBox = document.getElementById('text');
var current, min = 6, max = 14;
current = textBox.style.fontSize.substr(0, textBox.style.fontSize.length - 2);
current = parseInt(current);
if (textBox.clientHeight < textBox.scrollHeight) {
while (textBox.clientHeight < textBox.scrollHeight) {
current--;
if (current < min) break;
textBox.style.fontSize = '' + current + 'pt';
}
} else if (textBox.clientHeight > textBox.scrollHeight) {
while (textBox.clientHeight > textBox.scrollHeight) {
current++;
if (current > max) break;
textBox.style.fontSize = '' + current + 'pt';
}
}
For reference, here is the HTML structure:
<div id="text" contenteditable="true"></div>
And the CSS styles applied to the div:
#text {
position: relative;
border: 1px solid blue;
top: 180px;
left: 31px;
width: 300px;
height: 132px;
padding: 5px;
font-family: 'mplantin';
font-size: 14pt;
font-weight: 200;
}