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
I'll have to check that out. Thanks jonas-e.
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 + "\
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?
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.
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.
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.
@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 ..
"tedious" is a relative term and so is subjective.