How to declare global variables?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • fcfpoon
    New Member
    • Sep 2008
    • 1

    How to declare global variables?

    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:
    Code:
    <script type="text/javascript">
    var value;
    function setValue(i)
      {
      value=i;
      }
    function content()
      {
      if (value==1)
        {
        document.write("<a href='cheungfai.html'>");
        document.write("<img src='images/IMG_0171s.jpg'/>");
        document.write("<p class='p3'>");
        document.write("Travel and Nature Portfolio");
        document.write("</p></a>");
        }
      }
    </script>
    In the <body> section:
    [HTML]<div class="leftfram e">
    <p class="p2" onclick="setVal ue(1)" />
    Felix Poon's Photography
    </p>
    </div>

    <div class="maincont ent">
    <p><script type="text/javascript">
    content();
    </script></p>
    </div>[/HTML]
    Last edited by acoder; Sep 26 '08, 11:35 AM. Reason: Added [code] tags
  • pronerd
    Recognized Expert Contributor
    • Nov 2006
    • 392

    #2
    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.

    Code:
    <p class="p2" onclick="setValue(1);content();" />

    Comment

    Working...