Announcement

Collapse
No announcement yet.

Few basic JavaScript questions

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

  • Few basic JavaScript questions

    Hi,

    Yes I know, this isn't a javascript board - but there seem to be some web people floating around, and I know you guys won't lead me astray.

    Ok bit of background - I am the computer support person for a financial aid office of a fairly large university. A few years ago, long before I was here, they had hired a GA to create a webpage for them, as no one in the office had the expertise. Unfortunately, she used it as her own personal learning playground, then quit. They've been trying to unravel what she did since then - it was evidently quite a mess. :shock: Our admin assistant has done a lovely job teaching herself HTML and has gotten everything cleaned up with one exception - the javascript that governs the mouseover menu on our pages.

    Enter me. We need to update those menus, and I figure it's a quiet week, I'll teach myself a bit of javascript, enough to fix the menus, then keep learning as I can. The problem is, there are 9 scripts, and 68 pages of javascript code - which seems to be a bit much for a 9 button mouseover menu. Also, it seems that she used cookbook-style scripts from the web, but only parts of each one she downloaded - I keep finding whole sections that appear to do nothing at all. SO... here are my questions:

    - If you define a variable in the first script - can you then use it in the next script?

    IE In script 1 I set the variable y = 7
    Can I then say in script 2, y*2 and get the number 14?

    - Do you have to define a variable before you use it?

    IE, The variable y is not set in script 1 or 2.
    Script 2 says "tell me what y*2 equals"
    Script 3 says y = 7
    Will script 2 then go and look through script 3 and come up with 14?

    I would give better RL examples of what I'm looking at, but I'm still not sure as to what I'm looking at. ops: If you all could help me understand the hierarchy of how scripts interact, that would make this go a lot quicker.

    Thanks for any help....
    Arakni Spellweaver
    51st level Erudite Enchantress
    Povar
    250 Jewelcraft + Grandmaster Trophy!

  • #2
    In general, all scripts on one page are run in order, from top to bottom. The exception to this is functions; I'll discuss those later.

    So, let's say you have the following in your HTML, from your examples:

    [code:1]
    <html>
    <head>
    ... random stuff here ...
    <script language="Javascript" src="script_1.js"></script>
    <script language="Javascript" src="script_2.js"></script>
    <script language="Javascript" src="script_3.js"></script>
    </head>
    <body>
    ... random stuff here ...
    </body>
    </html>
    [/code:1]

    In this case, it's as if you had all the code from script_1, then all the code from script_2, then all the code from script_3, in that order, right there in the page. You can treat it as if it were one big program.

    Normally, the code will be run from top to bottom, line by line, as it's written. However, functions are NOT run. Rather, they're "set aside" as a definition of what to do when you call the function later in your code. This is the same as any subroutines in other programming languages.

    Let's look at your examples.

    In script 1 I set the variable y = 7
    Can I then say in script 2, y*2 and get the number 14?
    Yes.

    - Do you have to define a variable before you use it?
    IE, The variable y is not set in script 1 or 2.
    Script 2 says "tell me what y*2 equals"
    Script 3 says y = 7
    Will script 2 then go and look through script 3 and come up with 14?
    No, you don't have to define variables. JavaScript allows you to start using a variable without declaring it with the var keyword. However, it's considered good practice to declare your variables and document each one with a comment at the top of your code -- same as with any other programming language. There are also special considerations to using var inside a function, but those are fairly advanced topics.

    However, in the example you provided, the line in script 2 will return zero. The reason is that all variables are assigned a "default value" if you use them before you explicitly set their value. If they're used as a number, the value is zero. So, in script 2, the value of y is zero. You do y*2 and get 0*2 = 0 for y. Script 3 then says y=7, so at the end of the scripts, y=7. Remember, it runs top to bottom.

    ** Edit **
    This section needs a bit of clarification. There are two ways to interpret the word "define" here. The technical terms are "declare" and "initialize".

    Declaring a variable means using the var keyword to create its name. Some languages require you to declare your variables before you can use them. This cuts down on errors since the program won't run if you use a variable without declaring it first. Javascript does NOT require you to use var on all variables; you can just start using them when you need them in the middle of your code. However, this is considered bad programming practice as it makes the code MUCH harder for others to read and understand. It's preferred that all variables be declared at the top of the code with a brief comment explaining what the variable is for.

    Initializing a variable means giving it its value before it's used the first time. Javascript will initialize variables to a default value of zero for numeric stuff and an empty string for text stuff.

    Based on your description, it sounds like you're asking whether a variable has to be initialized or not before you can use it. Technically, you don't have to initialize it, as JavaScript does that for you. However, if you want to set it to a value other than zero or an empty string, then yes, you must do so explicitly before using the variable.
    ** End edit **

    I mentioned functions a few times. Let's take a look at how those work. For example:
    [code:1]
    function AddThree (x)
    {
    var y;
    y = x + 3
    return y
    }

    var alpha
    var beta
    alpha = 7
    beta = AddThree(alpha)
    [/code:1]

    What this script does is create a function called AddThree. It takes one variable passed into it, referred to as X. It then adds three to X and returns the new value. (Note to experienced coders: I know this isn't the most efficient way to code this, and I know there are side effects to using var in a function. It's just an example.)

    When the Web page loads, it sees the function, memorizes the name, then skips to the end of the function. It then declares the two variables (the var lines) and sets the value of alpha to seven. Then it gets to the line that calls AddThree. It passes the value of alpha to X in the function. The function then adds three and returns the new value (ten). Then beta is set to the new value of ten.

    Note that the code for x and y wasn't run when the script went through it from top to bottom. Rather, it skipped over it until it saw the call for the function AddThree in the line "beta = AddThree(alpha)". You can call the AddThree function as many times as you wish in your code, but only after you've defined the function.

    Hope this helps. Let me know if you have any more questions.
    Sir KyrosKrane Sylvanblade
    Master Artisan (300 + GM Trophy in all) of Luclin (Veeshan)
    Master Fisherman (200) and possibly Drunk (2xx + 20%), not sober enough to tell!
    Lightbringer, Redeemer, and Valiant servant of Erollisi Marr

    Comment


    • #3
      KyrosKrane,

      Thank you SO much. That did make sense, and help quite a bit. I am all the way up to chapter 4 in my book (titled "Variables") so that helped a lot. I'm on to the second page of code now! (66 left to go)

      The part that's hanging me up is this, and I will type it as I see it, line by line:

      // Get positions for section buttons

      POSSIBLE_MENU_COUNT = 9;

      var topPosition = 5;

      TOTAL_BUTTON_WIDTH = 190;

      for (i=1 ; i<=POSSIBLE_MENU_COUNT ; i++) {

      eval ('var arMenu' + i + ' = " " ' ) ;

      }

      BUTTON_SPACING = 0 ;

      //-->
      Ok that's the end of the code. Now, what I think I'm looking at is (with my comments in dark blue italics):

      // Get positions for section buttons this is just a comment telling me what this section is for

      POSSIBLE_MENU_COUNT = 9; this is telling me how many things can be in the menu. I want to add 6 more buttons, so I should change this from 9 to 15

      var topPosition = 5; this is defining the variable called "topPosition"... not sure if I want/need to change this yet.

      TOTAL_BUTTON_WIDTH = 190; I think this is telling me that the buttons can't be wider than 190... haven't gotten that far in the book.

      for (i=1 ; i<=POSSIBLE_MENU_COUNT ; i++) {

      eval ('var arMenu' + i + ' = " " ' ) ;

      } Ok I know that this is a loop from the i=1 ; i<=POSSIBLE_MENU_COUNT ; i++ pattern. I saw an example of this in chapter 3 and they told me it would be talked about more in chapter 6 (which I should hit at about 3 PM at the current rate). I know that eval means to evaluate. I know that var arMenu is setting the variable arMenu but it's not initialized because we haven't told it what the value of arMenu is - right? I keep seeing references to arMenu and elMenu, and I know that there's another script called menu.js (this is all from a script called parse.js) so is it referring to something in menu.js, or are arMenu and elMenu just names of variables that have nothing to do with the menu.js script that comes along further down the page? And if they are variables, I see them named but I never see a arMenu = whatever or a elMenu = whatever, in any of the scripts. So why keep referencing it if you aren't going to ever initialize it?

      BUTTON_SPACING = 0 ;

      //-->
      Thanks again for all of your help. I hope this isn't taking up too much of your time.

      edited three times - to fix HTML, grammar, and to set the code off in a quote
      Arakni Spellweaver
      51st level Erudite Enchantress
      Povar
      250 Jewelcraft + Grandmaster Trophy!

      Comment


      • #4
        OK I know I'm replying to my own thing but I figured it out! arMenu is defined 6 scripts later, in a loop that specifies arMenu1 = blah, arMenu2=blah, etc, so I do have to set the POSSIBLE_MENU_COUNT to 15 so that when eval ( 'var arMenu' + i + ' = " " '); the count is correct.

        I think.

        I hope that made sense.

        Thanks again KyrosKrane!
        Arakni Spellweaver
        51st level Erudite Enchantress
        Povar
        250 Jewelcraft + Grandmaster Trophy!

        Comment


        • #5
          I'd like to add in a couple comments on the behaviour of variables;

          If you do not var (declare) your variables, Java will declare them for you in the Global scope.

          If you do, they're declared in the scope of your statement.

          For instance,if you have a function like this

          [code:1]function AddOne(x) {
          y = x + 1;
          return(y);
          }[/code:1]

          java will actually interpret it as if you'd written

          [code:1]var y;

          function AddOne(x) {
          y = x + 1;
          return(y);
          }[/code:1]

          Now, any function can see variables that are defined inside them, or outside of any other functions, on the "global" scope.

          Conversely, if you had

          [code:1]
          function AddOne(x) {
          var y;
          y = x + 1;
          return(y);
          } [/code:1]

          no other function would be able to see the variable y from inside AddOne, as it is considered "local" to the function. So, if you added to the second example, the following

          [code:1]function ShowY() {
          Alert(y);
          }[/code:1]
          it would fail, as y would not be known inside the ShowY function. Using it in the first example, would return the value just fine.

          Comment


          • #6
            One more completely random tip.

            When a variable name is written entirely in caps (like TOTAL_BUTTON_WIDTH), that often (but not always) indicates this value is a constant -- once you assign it a value once, it's not supposed to change. This convention is a hold-over from some other programming languages.

            So in this case, you're expected to set the TOTAL_BUTTON_WIDTH and POSSIBLE_MENU_COUNT values only once at the top of your code, and then that value is used everywhere else.
            Sir KyrosKrane Sylvanblade
            Master Artisan (300 + GM Trophy in all) of Luclin (Veeshan)
            Master Fisherman (200) and possibly Drunk (2xx + 20%), not sober enough to tell!
            Lightbringer, Redeemer, and Valiant servant of Erollisi Marr

            Comment


            • #7
              And you may want to research come CSS menues out there. THey are much more transparent, and generally compatable with modern browsers.
              Ngreth Thergn

              Ngreth nice Ogre. Ngreth not eat you. Well.... Ngreth not eat you if you still wiggle!
              Grandmaster Smith 250
              Master Tailor 200
              Ogres not dumb - we not lose entire city to froggies

              Comment


              • #8
                A small update on what I ended up doing.

                Once I thought I had a bit of a handle on javascript I started trying to work with what we had. No go. I went out to the web, because I thought that she may have pulled them off the web as "cookie cutter" or "insert your pic here" sort of things - she had, but they were changed enough that they didn't work the way the website people said they should.

                Then I noticed at the very top of our code - the pages were all created with FrontPage. We use Dreamweaver. Which shouldn't matter much, but I know that the person who originally created it was asked to create it in Dreamweaver, since that's what we use, and that she had agreed to, and chose to do her own thing anyways. So if she didn't use the program requested, what else did she do that we didn't request?

                At that point I said to heck with it and rebuilt everything using Dreamweaver. I created a DW template and used Fireworks to create our rollover menu and our image maps. I'm in the process of pulling the text of all of our pages out of the old framework and shoving them into the new template. Once they're all in, it's a simple matter (if multi-step and time consuming) for our admin assistant to go into Fireworks and edit the template however she wants - including changing the rollover menu if she wishes. (Which is how this whole odessy got started in the first place. I just wanted to add a button to our rollover menu...)

                We know how to use Dreamweaver and Fireworks. It's taken me some time to redo the site using a DW template, etc., but considering that that's what we were supposed to get in the first place - a site that was easily manageable using just those two programs - I think it was worth the time investment.

                Thanks for all the help though
                Arakni Spellweaver
                51st level Erudite Enchantress
                Povar
                250 Jewelcraft + Grandmaster Trophy!

                Comment

                Working...
                X