0

This is the code I'm using to get the client width as a JavaScript whole number variable so that I can perform operations on it.

var width1;
window.onload = function()
{
    width1 = document.body.clientWidth;
}
var width = parseInt(width1);

The variable width is return NaN.

alex
  • 479,566
  • 201
  • 878
  • 984
Rumple
  • 198
  • 1
  • 9
  • 4
    yes it is, because window.onload doesn't execute until the document is loaded, but the parseInt is run immediately – Jaromanda X Jul 31 '15 at 00:27
  • Ok, I added the onload because the client width was not registering (says undefined) without it, is there a workaround? – Rumple Jul 31 '15 at 00:29
  • I wouldn't say there's a workaround except to change how you program knowing that not everything is synchronous, and knowing when something is asynchronous is a big advantage – Jaromanda X Jul 31 '15 at 00:32
  • Asynchronous, asynchronous, asynchronous. After you do some research on your own for what an asynchronous callback is and when it is called, you will understand much better why your code executes in the order it does. This is one of the first advanced concepts one must learn to write Javascript in a browser. – jfriend00 Jul 31 '15 at 00:38
  • The workaround is to put everything inside `window.onload`. If that feels strange don't worry, it's perfectly normal in javascript. – slebetman Jul 31 '15 at 00:48

1 Answers1

0

The code you have written isn't executed top to bottom, waiting for functions to be executed that are defined - the function assigned to window.onload is deferred until that event is satisfied, that is the, window has loaded.

Any post-processing of that value needs to happen in that callback too.

window.onload = function() {
    var width = parseInt(document.body.clientWidth);
    // Now do your work with `width` here.
}

Further reading

Also, the brace style you're using isn't recommended in JavaScript, as some parts of the language don't function as you may intend if you use it to return an object literal, for example.

return 
{
    prop: 'value'
}

The grammar says there can't be a line terminator after return, so you would get the standard return undefined behaviour, with an orphaned object literal.

Community
  • 1
  • 1
alex
  • 479,566
  • 201
  • 878
  • 984
  • The code **is** executed top down! Otherwise, yeah, all good. ;-) – RobG Jul 31 '15 at 01:42
  • @RobG Yeah, it's hard to explain that. What I meant is that if the interpreter sees a function assigned somewhere, it's not gonna halt and wait for it to be executed. :D – alex Jul 31 '15 at 02:24