Reputation:
I want to auto-translate a text on my website by exchanging it with the same sentence in another language every few seconds, but this is not where my problem lies.
I already got the JS for this set-up, it looks like this:
jQuery(function ($) {
var languages = ["¡Hola, me llamo X! Bienvenido a mi página web.", "Hallo, ich heiße X. Willkommen auf meiner Webseite.", "你好, 我叫 X。欢迎来到我的网站。"];
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 adjust the font-size
of my h2
to always fit 1 line to prevent shifting the following text further up and down, when the text-length changes.
Looks especially bad on mobile.
I tried using the open-source JS "jtextfill", but it doesn't work.
Upvotes: 3
Views: 991
Reputation: 14022
The idea of changing font-size
of text is not hard here.
font-size
of text to some variable.font-size
body
, but you can change it) and width of text element (#translate
in current case).font-size
by some value (for example by 0.1px
) and go to step 3. If no then that's all.Don't forget to make you h2
inline block to make it width defined by content and add white-space: nowrap
to prevent text moving to 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>
Upvotes: 2
Reputation: 378
Hope this will work:
http://simplefocus.com/flowtype/
$('h2').flowtype({
minFont : 10,
maxFont : 40,
minimum : 500,
maximum : 1200,
fontRatio : 70
});
Upvotes: 0