0

I am trying to make a javascript code, but it won't work. First time writing java, and it's a simple thing i'm trying to do, so it's probably a simple solution ;). The code underneath is in the section of my page.

<script language="javascript">
window.onload=function(){ 
var scherm = $( window ).width();
if (scherm > 971){
var x ="<td class='links'>";
var y ="<td class='rechts'>";
var z ="</td>";
}
else{
var x ="<tr class='links'>";
var y ="<tr class='rechts'>";
var z ="</tr>";
} };
</script>

So firstly I am trying to get the user's browser size. Depending on what that is I want set variable x,y and z. These I would like to echo later on in my html. I have tried that as follows (for x):

 <script>document.write(x)</script>

this returns the following error in google chrome:

Uncaught ReferenceError: x is not defined 
3
  • document.write(x) needs to be inside window.onload function, as x was only declared inside that scope Commented Apr 11, 2014 at 18:04
  • @juvian if that were to be done, the result would be to obliterate everything else on the page. Commented Apr 11, 2014 at 18:06
  • To do this, would I have to put my first script in the html body? Or is there another way to do this? Thanks for your quick reply by the way :) Commented Apr 11, 2014 at 18:07

1 Answer 1

1

You're getting that error because you're declaring those variables with var inside that load handler function. They're local to the function, and you won't have access to them outside the function.

Even if you were to fix that, your code won't work. The variables are initialized when the "load" event is fired, which will happen after your document.write() call. Using document.write() is generally a bad idea anyway; you're better off using DOM manipulation APIs to do what you need to do (whatever that is).

Sign up to request clarification or add additional context in comments.

1 Comment

@Jeroen well the topic of the DOM and its programming model is pretty broad. The browser turns the HTML into a data structure built from objects that expose various properties and methods. Here is a starting point.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.