By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
457,967 Members | 1,244 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 457,967 IT Pros & Developers. It's quick & easy.

How to declare global variables?

P: 1
I'm trying to develop a website with a left frame div and a main div, whereby the content of the main div changes depending on what you click on in the frame div. I'm trying to achieve this with onclick, which calls a function setValue(i) and sets the global variable value. From my main div I call a function content() which has if...else statements to display different content depending on the value variable. But for some reason, even though I'm declaring value outside of any functions, when setValue assigns a number to value, it doesn't seem to carry into the function content(). Can anyone help me figure out what I'm doing wrong? I've looked it over and over, and researched online, and can't figure it out. I've just started learning Javascript, so it's probably something really simple. The code is below:

In the <head> section:
Expand|Select|Wrap|Line Numbers
  1. <script type="text/javascript">
  2. var value;
  3. function setValue(i)
  4.   {
  5.   value=i;
  6.   }
  7. function content()
  8.   {
  9.   if (value==1)
  10.     {
  11.     document.write("<a href='cheungfai.html'>");
  12.     document.write("<img src='images/IMG_0171s.jpg'/>");
  13.     document.write("<p class='p3'>");
  14.     document.write("Travel and Nature Portfolio");
  15.     document.write("</p></a>");
  16.     }
  17.   }
  18. </script>
In the <body> section:
[HTML]<div class="leftframe">
<p class="p2" onclick="setValue(1)" />
Felix Poon's Photography

<div class="maincontent">
<p><script type="text/javascript">
Sep 25 '08 #1
Share this Question
Share on Google+
1 Reply

Expert 100+
P: 392
There is nothing wrought with your variable scope. In the code you provided you are never calling the content() function after the onClick event. The content() function is being run one time when the page loads, and is never called again.

You need to call the function you want to run as part of the event it is triggering off of.

Expand|Select|Wrap|Line Numbers
  2. <p class="p2" onclick="setValue(1);content();" />
Sep 25 '08 #2

Post your reply

Sign in to post your reply or Sign up for a free account.