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.
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.
Share Improve this question asked Jun 25, 2011 at 19:48 JacobTheDevJacobTheDev 18.6k29 gold badges102 silver badges161 bronze badges 2- 1 Why not look in the jQuery source code to see how they did it? – Chris Laplante Commented Jun 25, 2011 at 19:51
- Oo that might be a good idea if I can't figure it out another way, thanks. – JacobTheDev Commented Jun 25, 2011 at 20:02
5 Answers
Reset to default 3You'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);
}
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.
If you want to see how jQuery does it, here is the link to the source: https://github./jquery/jquery/blob/master/src/dimensions.js
I would use jQuery to do such a thing. You can find the exact thing you want right here: http://api.jquery./width/
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
);
}