nichemtktg — 2011-11-22T16:15:00-05:00 — #1
If I have a div that's 300px by 20px, is there a function that calculates whether a string will display with a line break, given font-size of 21px?
If not, I'll have to create some code, but if it's already available, that's even better
jonas_e — 2011-11-22T16:54:07-05:00 — #2
nichemtktg — 2011-11-22T19:30:13-05:00 — #3
I'll have to check that out. Thanks jonas-e.
system — 2011-11-22T19:59:40-05:00 — #4
Hopefully there is an easier way, but this "off the cuff" example should help you get started.
It displays the rendered width and height of a string based on its css styles. If you change the css styles for the string you can see the effect they have on the calculated width and height of the rendered text.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
var strTesterO = document.getElementById('strTester')
var str = "The cow jumped over the moon";
var spanO = document.createElement('span');
spanO.id = 'mySpan'
alert(document.getElementById('mySpan').clientWidth + "\
jonas_e — 2011-11-23T02:45:28-05:00 — #5
nichemtktg — 2011-11-23T11:08:55-05:00 — #6
I'm not familiar with window.onload. I understand what it does in the script, but can't find a reference that says onload is a property of window. Am I thinking about it correctly?
system — 2011-11-23T16:28:32-05:00 — #7
There's lots of references to window.onload on Google.
Basically, the onload event for the window is triggered when the page has finished loading after which the code within the function is executed.
paul_wilkins — 2011-11-24T06:24:27-05:00 — #8
The very best solution that I've come across for this is to use a hidden copy of that div, where you put the string in that hidden copy and work out if a line break occurs in that hidden div.
jonas_e — 2011-11-24T07:49:36-05:00 — #9
system — 2011-11-24T16:14:58-05:00 — #10
jonas_e — 2011-11-25T03:06:14-05:00 — #11
I guess it depends. I prefer the simplicity of jQuery which might be easier to understand for someone with little js knowledge:
$('#strTester').html('<span id="mySpan">The cow jumped over the moon</span>');
var mySpan = $('#mySpan');
Remember to include this in your page:
And to check out the documentation:
In this case particularly:
I trust that the jQuery team has performance as a top priority. Using $(document).ready() is more generic than using window.onload because you can use the first more times but the latter only once on a page.
system — 2011-11-25T03:55:12-05:00 — #12
jonas_e — 2011-11-25T04:05:21-05:00 — #13
@webdev1958: You're probably right. The reason why I appreciate jQuery so much, is because I know how tedious the same tasks are in plain js - because I learned that first ..
system — 2011-11-25T04:07:57-05:00 — #14
"tedious" is a relative term and so is subjective.