www.webdeveloper.com
Results 1 to 8 of 8

Thread: About Global variables

  1. #1
    Join Date
    Aug 2009
    Posts
    13

    Question About Global variables

    I have a question about global variable behavior in js.
    I have a script running inside a div (id1) that gets a variable from a php file.
    I have another script in a different div (id2) where I check for that variable's values.

    Except in the second div the variable loses its value.

  2. #2
    Join Date
    Aug 2009
    Posts
    13
    I have tried using the window.myVariable statment as well.

  3. #3
    Join Date
    Jan 2009
    Posts
    3,346
    You'll need to post some code before anyone will be able to help you. There just isn't enough information given to make an educated guess or wave a magic wand to fix it.

  4. #4
    Join Date
    Aug 2009
    Posts
    13
    <div id = "moduleX">

    <script type="text/javascript">

    var ft = 1;
    ft = 1;
    function runs() {
    ft = ft + 1;
    }


    window.onload = function () {
    runs();
    };
    </script>

    </div>

    <div id = "moduleY">

    <script type="text/javascript">

    document.write(ft);

    </script>
    </div>

    The result should be 2. but it is not.

  5. #5
    Join Date
    Aug 2009
    Posts
    593
    Your getting the number 1 because document.write(ft); is being executed before window.onload. window.onload runs only when the page has finished loading.

  6. #6
    Join Date
    Dec 2002
    Location
    Pleasanton, CA
    Posts
    2,132
    Code:
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    
    <html lang="en">
    <head><title>untitled</title>
    <script type="text/javascript">
    // Move ft into the <head> section and you don't need to set it to 1 twice
    var ft = 1;
    </script>
    </head>
    
    <body>
    
    <div id = "moduleX">
    <script type="text/javascript">
    function runs() {
    	ft++;  // same as ft = ft+1;
    }
    // You don't need the onload function in this case. runs() gets called as this
    // div is loaded
    runs();
    </script>
    </div>
    
    <div id = "moduleY">
    <script type="text/javascript">
    	document.write(ft);
    </script>
    </div>
    
    </body>
    </html>

  7. #7
    Join Date
    Aug 2009
    Posts
    13
    thanks Dash, erm... what about setTimeout? XMLHttpRequest() Object? do these run after page has finished loading?

  8. #8
    Join Date
    Aug 2009
    Posts
    13
    Thank you Nedals.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles