Totty.js
Totty.js

Reputation: 15831

How to calculate the width of a <div> tag for example based on characters in javascript?

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

Answers (5)

Marwan
Marwan

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

Oscar Godson
Oscar Godson

Reputation: 32726

Jesus you guys, JavaScript !== jQuery. Anyways, to get a width of an element with JavaScript you can use offsetWidth like this:

http://jsfiddle.net/gJyKV/1/

(code)

document.getElementById('test').offsetWidth

If will get the current width even if it's absolutely positioned!

Upvotes: 2

Joshua - Pendo
Joshua - Pendo

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

James Kovacs
James Kovacs

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.

http://jsfiddle.net/vW6Wp/

var test = $('<span>hello</span>').appendTo('body');
alert(test.width());

Upvotes: 1

Itay Moav -Malimovka
Itay Moav -Malimovka

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

Related Questions