Reputation: 15831
I need to create a tag that is absolutely positioned with a variable width, based on the string length, font, size...
Ex.:
<div>hello</div>
For this I would need about 50px of width. How to calulate this in Javascript? thanks
Upvotes: 4
Views: 1064
Reputation: 2402
I dont know why always people answer things with jquery ' is jquery is a standard for scripting language and if the guy need that item alone about the width of the div to load all that script . there is something called javascript guys .
sorry for this big talk but i just dont like it
@tooty you can get that with javascript by catching the div by id and then get the offsetWidth
document.getElementById('divId').offsetWidth
Regards
Upvotes: 1
Reputation: 32726
Jesus you guys, JavaScript !== jQuery. Anyways, to get a width of an element with JavaScript you can use offsetWidth
like this:
(code)
document.getElementById('test').offsetWidth
If will get the current width even if it's absolutely positioned!
Upvotes: 2
Reputation: 4371
I believe that the jQuery library also offer this. If you gave this div the ID 'get-width' the following could would give back the width:
$('#get-width').width();
You could give it a should by testing it with the following code:
<div id="test">hellloooo</div>
<script type="text/javascript">
$(document).ready(function() {
alert($('#test').width());
}
</script>
Upvotes: 1
Reputation: 11661
Create the text in a span, measure its rendered width, and then re-position it to taste. You can always render it off-screen and then re-position if you don't like the jump in position.
var test = $('<span>hello</span>').appendTo('body');
alert(test.width());
Upvotes: 1
Reputation: 53605
You do not need to do complex calculation, just use this (Dom way of getting the width of an element).
As you can see, way to complex as each browser has a different way to do it. that is the drive that made Mootools and the other JavaScript libraries into life in the first place. Do yourself a favor and use one of those libraries.
Here is the Mootools way.
Upvotes: 0