SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Member
    Join Date
    Feb 2005
    Posts
    18
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    javascript variable scope

    Hi All,

    I have a site that randomly chooses a background image when it loads. This was done fairly easily in javascript, and I have a variable (bkgnd_index) that stores which background was chosen. The reason for this is that the attributes of certain site elements (i.e. text colour, placement, etc.) vary depending on the background selection. I modify these CSS elements after checking my variable. So, everything works as expected and the javascript code is stored in an external file: mysite.js, and is referenced in the <head> section with a <script src="mysite.js" type="text/javascript"></script>.

    Now, the problem is, later on in the site (in the <body> section), I need to place a flash object, but the particular object is also dependent on my background choice. I am using javascript to embed the flash movie (for xhtml compliance), see here for the script. So, I am inside another <script></script> section, and can't seem to access my variable (bkgnd_index) for scope reasons, I suspect. Is there anyway to get at this variable?

    Thanks for any suggestions,
    Jim

  2. #2
    SitePoint Wizard
    Join Date
    Mar 2001
    Posts
    3,537
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Try this:

    Code:
    <html>
    <head><title></title>
    <script type="text/javascript" language="javascript">
    
    var a = 10;
    
    </script>
    </head>
    <body>
    
    <script type="text/javascript">
    
    alert(a);
    
    </script>
    </body>
    </html>

  3. #3
    SitePoint Evangelist SpaceFrog's Avatar
    Join Date
    Jan 2005
    Location
    Outerspace
    Posts
    511
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    or declare your varaible as a window variable in function

    Code:
    window['globalvar']="told you I was global"


Bookmarks

Posting Permissions

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