In the future please post a new question in a new thread like here where I've moved this. Do not interrupt an existing thread, especially not before the original person has had a chance to respond to the initial advice.
OK, the original solution - what I think you were asking about - was:
Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
function findwidth(){
var width = document.getElementById('test').offsetWidth;
alert(width);
}
</script>
</head>
<body onload="findwidth();">
<div style="width:965px">
<div style="width:100%" align="center">
<div style="width:365px" align="center">
<div id="test">
</div>
</div>
</div>
</div>
</body>
</html>
Your code would work if written with the proper syntax. Instead of:
Code:
window.onload=findwidth();// doesnt work
use:
Code:
window.onload=findwidth;// does work
Or:
Code:
window.onload=function(){findwidth();};// does work
However, none of that is all that ideal. All three working approaches pollute the global scope unnecessarily, and all three take control of the onload event in such a way that is exclusive and subject to being overwritten by other scripts that might do the same thing.
To do this 'right' (there's no absolute right or wrong way), I might do:
Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript">
(function(){
function findwidth(){
var width = document.getElementById('test').offsetWidth;
alert(width);
}
if (window.addEventListener){
window.addEventListener('load', findwidth, false);
}
else if (window.attachEvent){
window.attachEvent('onload', findwidth);
}
})();
</script>
</head>
<body>
<div style="width:965px">
<div style="width:100%" align="center">
<div style="width:365px" align="center">
<div id="test">
</div>
</div>
</div>
</div>
</body>
</html>
Or:
Code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<div style="width:965px">
<div style="width:100%" align="center">
<div style="width:365px" align="center">
<div id="test">
</div>
</div>
</div>
</div>
<script type="text/javascript">
(function(){
var width = document.getElementById('test').offsetWidth;
alert(width);
})();
</script>
</body>
</html>
Neither of which require or are exposed to the onload event of the body or window, and neither of which have any variables or function names in the global scope. There are at least several variations on these two general approaches. Perhaps there's even another approach or approaches.
Bookmarks