JacobTheDev
JacobTheDev

Reputation: 18510

Read the width of a div with JavaScript

I'm trying to read the width of a div without jQuery. The code I'm using is:

JS:

var windowwidth = parseInt(document.getElementById("window").style.width);
window.onload = function start() {
    alert(windowwidth);
}

HTML:

<div id="window">
    <p>Lorem ipsum dolor sit amet.</p>
</div>

CSS:

#window {
    height: 250px;
    margin: 0 auto;
    width: 600px;
}

I don't understand why this isn't working, I've looked all over this site and google and can't figure out a solution. I don't want to use jQuery for this (it's a small custom HTML5 script so I don't need that huge library for one little thing) and even when I try the jQuery method, it still doesn't work.

Upvotes: 1

Views: 3042

Answers (5)

redexp
redexp

Reputation: 5065

You can get style.width only after the element is drawn. Try to put your code to setTimeout(). Sometimes it helps me

window.onload = function(){
    setTimeout(
       function(){ alert(document.getElementById('window').style.width); },
       200
    );
}

Upvotes: 0

user578895
user578895

Reputation:

don't read the style property, read the actual width of the element:

window.onload = function(){
    alert(document.getElementById('window').offsetWidth);
}

offsetWidth is what the browser says is the width, which can be different than what you're setting it to with CSS if, for example, the content stretches it wider.

Upvotes: 2

Chris Laplante
Chris Laplante

Reputation: 29658

If you want to see how jQuery does it, here is the link to the source: https://github.com/jquery/jquery/blob/master/src/dimensions.js

Upvotes: 1

davin
davin

Reputation: 45525

You're not guaranteed that document.getElementById() will work (i.e. will return the required element) before the DOM is ready. So try:

window.onload = function() { // removed the name to avoid some IE leaks
    var windowwidth = parseInt(document.getElementById("window").style.width);
    alert(windowwidth);
}

Upvotes: 3

ju5tu5
ju5tu5

Reputation: 36

I would use jQuery to do such a thing. You can find the exact thing you want right here: http://api.jquery.com/width/

Upvotes: 0

Related Questions