Auto adjust font size in specific DIV with text change
I want to automatically translate text to my site, exchanging it with the same sentence in a different language every few seconds, but that's not where my problem is.
I already got the JS for this setup, it looks like this:
jQuery(function ($) {
var languages = ["¡Hola, me llamo Jan! Bienvenido a mi página web.", "Hallo, ich heiße Jan. Willkommen auf meiner Webseite.", "你好, 我叫 Jan。欢迎来到我的网站。"];
var counter = 0;
var $exc = $('#translate')
setInterval(function () {
$exc.text(languages[counter++]);
if (counter >= languages.length) {
counter = 0;
}
}, 1600)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h2 id="translate">你好, 我叫 Jan。欢迎来到我的网站。</h2>
Now I want to set font-size
mine h2
to always fit 1 line to prevent the next text from shifting further up and down when the text length changes. Especially looks on mobile devices.
I tried using the open source JS "jtextfill" but it doesn't work.
source to share
The idea of changing the text font-size
is not difficult here.
- Store the default (current)
font-size
text for some variable. - After applying the translation, apply the default
font-size
- Compare the width of the container (in our case it will be
body
, but you can change it) and the width of the text element (#translate
in the current case). - If the width of the text element is greater than the width of the container, decrease it
font-size
by some value (for example, by0.1px
) and go to step 3. If not, then that's it.
Don't forget to make an inline block h2
to make it the content-specific width, and add white-space: nowrap
it to prevent the text from moving to the next line and allow our calculations.
Demo:
jQuery(function ($) {
var languages = ["¡Hola, me llamo Jan! Bienvenido a mi página web.", "Hallo, ich heiße Jan. Willkommen auf meiner Webseite.", "你好, 我叫 Jan。欢迎来到我的网站。"];
var counter = 0;
var $exc = $('#translate');
var defaultFontSize = parseFloat($exc.css("font-size"));
function adjustFontSize() {
var fontSize = defaultFontSize;
$exc.css("font-size", fontSize + "px");
while ($("body").width() < $exc.width()) {
fontSize -= 0.1;
$exc.css("font-size", fontSize + "px");
}
};
adjustFontSize();
setInterval(function () {
$exc.text(languages[counter++]);
adjustFontSize();
if (counter >= languages.length) {
counter = 0;
}
}, 1600)
})
body {
/* just 300px width for demo */
width: 300px;
/* just styles for demo */
border-right: 1px dotted gray;
height: 100vh;
margin: 0;
}
#translate {
/* take width and disable line wrapping */
display: inline-block;
white-space: nowrap;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<h2 id="translate">你好, 我叫 Jan。欢迎来到我的网站。</h2>
source to share
Hope this works:
http://simplefocus.com/flowtype/
$('h2').flowtype({
minFont : 10,
maxFont : 40,
minimum : 500,
maximum : 1200,
fontRatio : 70
});
source to share