Sunday, June 24, 2007

Summer 2007

week 7: 6/24

Hello all,
    I know a lot of you are having a difficult time with the first part of the mid-term project, but keep plugging and trying to figure it out.
    The key is test your scripts, and then re-test and re-test and re-test. There really is no other way. First, it helps you to begin to understand how the script works, and then how to solve the problem at hand.

If you do not understand the original script, there is no way you can do this mid-term.

    Also, using alert() functions here and there to monitor your scripts and the data helps a lot too. You can always take them out when you're finished working on it.
    Anyway, I'm around if you want help. See you tomorrow. Carter-

  1. TOPICS:
    • LINK   Review: creating a simple html table;
    • LINK   Review: putting a form into a table;
    • LINK   Review: Creating a layer with CSS;
    • LINK   Review: getElementById() function,
    • LINK   Review: event handlers,
    • LINK   Mid-Term: The script from the hand-out.

  2. HOMEWORKMid-Term Project, Part I: use the reading that I handed out in class, and the CSS & HTML file that we created in class, along with the script given on the last page of the handout to create a MULTIPLICATION TABLE. Everyone should start with the script given to you, but then you should modify it to contain not only the alert() function, but also a function which prints the table out into the 2nd layer.
     
  3. Review:
    1. Tables—See below the creation of a very simple table with five (5) rows and five (5) cells in each row:

        <table border="0px" width="100%">
      1  <tr>
            <td colspan="5">&nbsp;</td>
          </tr>
      2   <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
      3   <tr>
            <td colspan="5">&nbsp;</td>
          </tr>
      4   <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
      5   <tr>
            <td colspan="5">&nbsp;</td>
          </tr>
        </table>
      This code creates the table that you see below:

       
           
       
           
       

      Next, here are a couple of tables with the width of a few cells changed, made narrower, plus with the addition of the form elements. The code is place below the tables:

       
           
       
           
       

       
    2. Forms—In the next table, the form has been added to it. Below, you will find the code to create this table:

       
       type a number  
       
          
       

      <form name="myForm" id="myForm"/>
        <table border="0px" width="100%">
      1  <tr>
            <td colspan="5">&nbsp;</td>
          </tr>
      2   <tr>
            <td width="10px">&nbsp;</td>
            <td align="right">type a number</td>
            <td width="200px">
             <input type="text" id="userNum"/>
           </td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
      3   <tr>
            <td colspan="5">&nbsp;</td>
          </tr>
      4   <tr>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
            <td>
             <input type="button" id="submit" value="submit">
           </td>
            <td>&nbsp;</td>
            <td>&nbsp;</td>
          </tr>
      5   <tr>
            <td colspan="5">&nbsp;</td>
          </tr>
        </table>
      </form>

      When the borders are turned off, the table should look like this:

       
       type a number  
       
          
       
       
    3. CSS Layer—In the next table, the form has been added to it. Below, you will find the code to create this table:Next, the div tags are added before the first </form> tag and after the last one, along with a CSS #ID to style and create a layer:

        <style type="text/css">
         <!--
          #layer1  {width:250px;
                    height:100px;
                    top:10px;
                    left:100px;
                    position:absolute;
                    z-index:1;
                    border-width:3px;
                    border-style:double;
                    border-color:#ccaaff;
                    font-family:Arial;
                    background-color:#110022;}
         //-->
        </style>

      The first <div> tag must also have the same ID as indicated in the CSS above, like so:
         <div id="layer1">
      This will change the simple table and form into a layer that may be positioned anywhere on the table. In addition, the ID will make the entire layer accessible to manipulation by our JavaScript.

       
       type a number  
       
          
       

      Below, another CSS ID is added; however, in order for this to show up in the page, another pair of <div> must be added with the second ID, shown below applied

        <style type="text/css">
         <!--
          #layer1  {width:250px;
                    height:100px;
                    top:10px;
                    left:100px;
                    position:absolute;
                    z-index:1;
                    border-width:3px;
                    border-style:double;
                    border-color:#ccaaff;
                    font-family:Arial;
                    background-color:#110022;}

          #layer2  {width:250px;
                    height:100px;
                    top:120px;
                    left:100px;
                    position:absolute;
                    z-index:2;
                    border-width:3px;
                    border-style:double;
                    border-color:#ccaaff;
                    font-family:Arial;
                    background-color:#110022;}

         //-->
        </style>

      And then down below in the HTML of the document, together with the ID:

          <div id="layer2">&nbsp;</div>
      With this new ID, then, applied to a second pair of <div> tags, a new layer is created, even though there is nothing but a blank space between the two tags of the second layer:

       
       type a number  
       
          
       

       
       
    4. document.getElementById()—If you recall from prior weeks, this function takes the action of searching through the entire document for a particular ID. Recall that ID's are assigned in a tag, and they may also be used by CSS to create layers, as we have done. We have also given IDs to our form elements. IDs are used by JavaScript to locate an item, this is why each ID must be unique. No two IDs can have the same name. JavaScript, once an ID is located, can manipulate the element in many ways.
          If a form element has an ID, then JavaScript can use the ID to extract data from it by calling on its value. The value of a text box is whatever the user types in the box, and the way JavaScript extracts it is as follows:

          document.getElementById("userNum").value
      This refers to whatever the user types in the box. If the user types nothing in the box, then the value is nothing. Once the data in the text box is extracted, however, in order for it to be used or manipulated, it must be stored in a variable. This is done like so:
          var multiple = document.getElementById("userNum").value
      Now, whatever the user types in the box will immediately be transferred and stored into the variable multiple, and, as you know, many things can be done with variables and the data stored inside of them.
       
    5. Event Handlers—As mentioned in prior classes, an event here refers to computer events, such as loading a web-page, or closing a web-page, or clicking on a button or link, or tapping the enter key. All of these are events among many others defined by JavaScript.
          Now, JavaScript can use these defined events to cause yet other events to occur. For example, as mentioned, the clicking of a mouse is an event and this event could cause another event, like the appearance of an alert box over the browser window. It may do so with the event handler known as onclick:
      onclick = "alert('hello')";
          This is also the event handler that we will use for the submit button in our form, but instead of calling an alert() function, we will call our own user-defined function, which we will name myTable():
          <input type="button" id="submit" value="submit" onclick="myTable()"/>
       
    6. Mid-Term Script—Once you get the HTML and CSS typed in your document and you have two layers similar to the ones shown above, and once you get the event handler typed into the button form element, it is time to type the script into the document. Since our event handler calls the myTable() function, then the name of our function in our script should be the same. It is as follows:

      <script language="javascript" type="text/javascript">
       <!- -

      1.   function myTable()
      2.   {
      3.     var multTable = prompt("Please enter a
      4.       number to create a multiplication
      5.       table","");
      6.     var theTable = "";
      7.     for(var i=1; i<=12; i++)
      8.     {
      9.       theTable += i + "x" +multTable+ "=" +(i
      10.        * multTable)+ "\n";
      11.     };
      12.     alert(theTable);
      13.    }

       //- - >
      </script>

      Now, let us go over this script line-by-line so that we can determine what is happening.

        Line 1:
        function myTable()
        Here is the simple function declaration including:
        1. the function keyword;
        2. the unique name of the function: myTable;
        3. the opening and closing parentheses; and
        4. the opening, line 2, and closing line 13, curly brackets for the entire function.

        Lines 3-5:
        var multTable = prompt("Please enter a number to generate a multiplication table","");
        The first variable declaration and its initialization including:
        1. the var keyword;
        2. the unique name of the variable: multTable;
        3. the assignment operator; and
        4. the prompt() function which requests data from the user.

        Line 6:
        var theTable = "";
        The second variable declaration and its initialization including:
        1. the var keyword;
        2. the unique name of the variable: theTable;
        3. the assignment operator; and
        4. the value assigned, which is an empty string. Without this, the value of the variable would be undefined or null. Try removing the = "" from this statement to see how it affects the entire function when run.

        Line 7:
        for(var i=1; i<=12; i++)
        The initialization of the for loop including:
        1. the for keyword;
        2. the initial value of the counter variable, i = 1: theTable;
        3. the test condition, i <= 12;
        4. the incrementation of the counter variable, i++; and
        5. the opening, line 8 and closing line 11 curly brackets of the for loop.

        Line 9:
        theTable += i + "x" +multTable+ "=" +(i * multTable)+ "\n";
        This line assigns the variable, theTable, a new value, and by doing so, what we have is the heart of this script. It creates the multiplication table one line at at time in the following way:
        1. assigns the variable, theTable, with a new value with the assignment operator +=. This operator retains the existing value and adds it to a new value, so the result is a combination of the previous value AND the new value.
        2. next, begins the concatentation of a line of the multiplication table with the value of i. The first time through the loop i = 1. The second time, i = 2, the third, i = 3, and so on up to 12.
        3. the second term of the concatenation is just a very short string, the character "X", which will represent the 'times' sign in the multiplication table;
        4. the third term of the concatenation is the value of the variable multTable, which is simply whatever the number the user typed in at the prompt function.
        5. the fourth term of the concatenation is another very short string, the character "=", which will represent the 'equal' sign in the multiplication table;
        6. the fifth term of the concatenation is a brief operation in which two variables are multiplied, i * multTable, the counter variable multiplied by the user's number. This is last number of each line of the table after the equal sign.
        7. the sixth term of the concatenation is the final short string, the escape character "\n", which is really just a hard return for the alert window, the equivalent of the <br/> for HTML.
        8. the result of the concatenation of these six terms will be a single line of the multiplication table. If it is the first line, then the result will be this string:
          "1 X 10 = 10".

        Line 12:
        alert(theTable);
        This is the final output of the multiplication table, contained within the variable, theTable, in an alert() function.

      Once you get the script to work, you will be able to click on the submit button in the form to activate it, or call the function; however, as the script is now written, it completely bypasses the input field of the form. Instead, it provides a prompt()function.
          Therefore, just getting the script to function is only the very beginning of this problem: what you must do to complete this script for Part I of the mid-term project are three things:

      1. eliminate the prompt()function;
      2. activate the form text field as the source for data input instead of the prompt();
      3. print out the results of the script (produce the output) in the other blank layer.

      Below, you should find an example. Type a number in the form field, and then click submit:
       
       type a number  
       
          
       



Sunday, June 17, 2007

Summer 2007

week 6: 6/17

Hello my friends,
You guys did well on Friday. I know it was a hard class, but I think a lot of what we did will sink in more as we get to the next few weeks. Please keep plugging and don't stop practicing.
    That being said, let's get down to business: creating a bar graph on-the-fly. In this posting, I will continue from the previous posting. Although it was a rather difficult script we wrote in the last class compared to others we have done so far in class, it was actually the first real and useful application of JavaScript we have seen. We didn't simply learn about a particular statement type or term, such as conditional statements or variables and use them in a couple examples. NO, we actually put to use much of what we have learned so far into an actual script that has real benefit. We didn't just figure out if a number was odd or even, we magically created and modified web-content in the form of an instant and colorful bar graph with little more than a JavaScript script.
    Although I cannot say that things will get any easier from here, I can certainly say that they will not get any more difficult. Because it had so many parts, and because it involved a form, that was one of the more difficult scripts we will contend with during this entire term. Moreover, it has a great many similarities to the form validation that we will start to cover in a couple weeks, and which you will use on your final project. As a result, some of what we did last week, you will see again (and again) in class, and hopefully then it won't be quite as hard as it was the first time.

    And finally, I want to inform everyone not to miss class next week (Friday, June 22) as I will be explaining the first part of the mid-term project on which we will spend time in class working. In this week's posting, you will see below I have a link for the take-home mid-term exam and the mid-term project, both due in three weeks. Carter-

  1. TOPICS:
    • LINK   Reviewing the getElementById() function,
    • LINK   Reviewing event handlers,

  2. HOMEWORK
    • LINK   Mid-Term Exam—due in three weeks.
      For extra credit in the exam, please see directions for a script below:
      • Create a script that requests a number from the user in a prompt() function or in a form element (as in Friday's class;
      • It should utilize a for() loop that loops the same number of times as the user's number—see the book for instructions on how to create a for() loop;
      • The for() loop should repeat an alert() function for each loop with a message inside such as this:
                   Click Here to see example:

    •       Mid-Term Project—also due in three weeks (see below for additional reading material to download for this project). You must construct a script that creates a multiplication table. I have yet to cover most of requirements for this project; however, I will address each issue in the next two classes. The reading below, however, should help you understand the beginning of the problem.

    • LINK   Reading—Download this reading by clicking on the LINK and. It will assist you in creating the Multiplication Table.



     
  3. Review:
    1. document.getElementById()—This is a JavaScript built-in function that selects the specified ID from the HTML code in the body of the document and that enables the script to manipulate it in some way. For example, if there is an ID by the name of "homework", the document.getElementById function may select it in this way:
        document.getElementById("homework").
      As a result, the script will activate the "homework" ID and then have the ability to do things with it or extract data from it. If it is an H1 tag or a H2 tag or a P tag, it may change the color of the text, or the size or various other properties. If it is a form element, it may be able to extract the data from it. It does so in this way:  document.getElementById("homework").value, where value is whatever is typed in the blank of the form element with that ID.
          In the form we typed last week, there were seven (7) form elements. We were able to extract whatever data the user types in those seven blanks with this new function. Below I create seven new variables, and then use the document.getElementById() function to move the data from the form elements into the variables. Finally, all is revealed with a series of alert() functions.

      <script language="javascript" type="text/javascript">
      <!--
      function writeText()
      {
        var homework = document.getElementById("hw").value;
        var classwork = document.getElementById("cw").value;
        var mtExam = document.getElementById("mtE").value;
        var mtProject = document.getElementById("mtP").value;
        var fExam = document.getElementById("fE").value;
        var fProject = document.getElementById("fP").value;
        var quiz = document.getElementById("q").value;

        alert(homework);
        alert(classwork);
        alert(mtExam);
        alert(mtProject);
        alert(fExam);
        alert(fProject);
        alert(quiz);
      }

      //-->
      </script>

       
    2. Event Handlers—In JavaScript there are a series of terms that cause things to happen, much like built-in functions; however, unlike them, event handlers make things occur as a result of certain 'computer events'. These events are peculiar to computers, events such as loading a browser window or web-page, or closing a web-page or browser window, such as clicking with the mouse or moving the cursor with the mouse. These are all events which occur in a computer environment. Event handlers use these events to cause other things to occur, such as making something appear or disappear when you click on a button with a mouse. The click of the mouse is the event that the event handlers handle. The appearance of a pop-down menu when you click on the mouse is the action that the event handlers cause to occur. Some common event handers are: onLoad, onUnload, onmouseOver, onmouseOut, onClick, etc.
          Like the <a> anchor tag, event handlers can be used to call or activate user-defined functions. We can use an event handler to activate our function above with the submit button in our form. We do this in the <input/> tag itself:
      <tr>
        <td colspan="3"> &nbsp;</td>
        <td>
         <input type="button" id="myButton" value="send" onclick="writeText()"/>
        </td>
        <td>&nbsp;</td>
      </tr>


  4. INTRODUCE: Images—As you already know, the document.write() function allows us to write data such as strings and numbers directly into a web-page, and that HTML tags can be included to format a page as any ordinary web-page. Up to now, we have only used text and numbers and formatted them with HTML; however, the <img/> tag is also HTML, so it may also be written into a page. Here is an example:
     document.write("img src = ‘images/ myPicture.jpg’ alt = ‘my picture’/>")
    Whatever the image is, it will now appear in the page if this statement is run in a script. But more can be done: in addition to the src and alt attributes for the <img/> tag are the width and height attributes. Knowing this gives us the opportunity to make the image size customizable depending on numbers input into the script. If we use the form from last week's class which request numbers, grades for each of the input blanks, we can adjust the size of the images with them. If each of the images is set to have the same height, say 10 pixels, but adjustable widths, then depending on the numbers input into the blanks we can change the widths of images.
        Type some numbers in the blanks below, then click submit to see how this operates.
     
    grade 1  
     
    grade 2  
     
      

    (type values in the blanks above, then click ENTER)

    How this works is not some magical mystery when you understand that everything written into a page such as this is a combination of plain text and HTML. You already know HTML, now all you need to do is find out how JavaScript put it there.

    1. The first step is to use ideas from the bit of script we already have, but instead of using the alert() function, we will use document.write() Further, instead of using seven variables and seven form fields, I will stick to just the two that I have above. Here is a comparison of how we left off in the last posting here, and how we're beginning in this one:

      OLD:

          <script language="javascript" type="text/javascript">
            <!--
            function writeText()
            {
              var grade1 = document.getElementById("g1").value;
              var grade2 = document.getElementById("g2").value;

              alert(grade1);
              alert(grade2);
            }

            //-->
          </script>


      NEW:
          <script language="javascript" type="text/javascript">
            <!--
            function writeText()
            {
              var grade1 = document.getElementById("g1").value;
              var grade2 = document.getElementById("g2").value;

              document.write(grade1);
              document.write(grade2);
            }

            //-->
          </script>


      As you can see, all that has been alterred is that the alert() function has been changed to the document.write() function.

    2. Now that we have done this, we can add the HTML, meaning the images. See the revised document.write() functions below:
        document.write("<img src=‘images/sky.gif’ alt=‘grade one’ height=‘10px’ width=‘10px’/>" + grade1);

        document.write("<img src=‘images/purple.gif’ alt=‘grade one’ height=‘10px’ width=‘10px’/>" + grade1);

      In addition to adding the image, I've used the alt, the src, the width, and the height attributes.
    3. Currently, the width and the height are set values of 10 for each image. They can, nonetheless, be made to vary depending on the values input at the form elements. Remember, the values typed into the form elements are stored in variables of the same names: grade1 and grade2. Those variables can be used as the value of the width attributes.
          Look closely at the example below, especially at the use of double-quotes (" ") and single-quotes (‘ ’).


        document.write("<img src = ‘images/sky.gif’ alt = ‘grade one’ height = ‘10px’ width = ‘" + grade1 + "px’/>" + grade1);

        document.write("<img src = ‘images/purple.gif’ alt = ‘grade two’ height = ‘10px’ width = ‘" + grade2 + "px’/>" + grade2);

      As a result of this revision, the height attribute for both images is set at 10 pixels but the width is set to some value grade1 or grade2. If the user types in 88 or 23, then that will be the new width of the image. Since my images are tiny .gif images created in Photoshop with only 1px in width and only 1px in height, when the width and height attributes of the <img/> tag are adjusted, they can become any size. The advantage is that the file size remains unchanged no matter what size the image become in the HTML document as a result of the script.
    4. If you revisit the function above, you will see that there is one bar for each input box, but that there is also third bar labelled average. Obviously, then, this is the average of the two grades entered into the blanks in the form above.
          To recall elementary school mathematics, to take an average of several numbers is to add up all the numbers and then dvide by how many numbers there are, such as: (A + B + C)/3   or   (A + B + C + D)/4. In the example for the script in this page, there are only two numbers, grade 1 and grade 2. To average them out, we simply add them together and then divide by two: (grade1 + grade2)/2. Therefore, we will revise the script again by adding a third variable with the average of the first two variables as its value:


          <script language="javascript" type="text/javascript">
            <!--
            function writeText()
            {
              var grade1 = document.getElementById("g1").value;
              var grade2 = document.getElementById("g2").value;
              var average = (grade1 + grade2)/2;

              document.write("<img src = ‘images/sky.gif’ alt = ‘grade one’ height = ‘10px’ width = ‘" + grade1 + "px’/>" + grade1);

              document.write("<img src = ‘images/sky.gif’ alt = ‘grade two’ height = ‘10px’ width = ‘" + grade2 + "px’/>" + grade2);

              document.write("<img src = ‘images/purple.gif’ alt = ‘average’ height = ‘10px’ width = ‘" + average + "px’/>" + average + " average");
            }

            //-->
          </script>

      In the above script, we've added a third variable and a third document.write(). However, you'll soon see, that if you run the script, the third document.write() will give you a very large number. This is because when the first two numbers are added together, concatenation is used instead of addition. Therefore, the numbers are put one right after the other instead of creating a sum, and 36 + 78 = 3678 instead of 114. This means that when the user types into the form fields, the data entered is string data even if numbers are used.
    5. To solve this problem, the data entered into the form fields must immediately converted from strings into numerical values. This is done, if you recall, by using the parseInt() function. To use this function, data or a data container is put between the parentheses of the function. One possible solution is as follows:
        var grade1 = document.getElementById("g1").value;
        var temp1 = parseInt(grade1);

        var grade2 = document.getElementById("g2").value;
        var temp2 = parseInt(grade2);


      This would solve the problem; however, it would also require the creation of 2 more variables-- temp1, temp2--and this is a bit repetitive and redundant.
          There is a way, however, to make a more efficient solution: convert the value with parseInt() before it gets put into the first variables, (grade1, grade2). This would eliminate the need for the temp1, temp2 variables.    As it is now,
      first, the value is put in the variable grade1 or grade2; and
      second, the value in the variable is converted by parseInt().
      But it would be much easier if we could parseInt() the value before it is put into the variable grade1 or grade2 instead of after.
    6. This is resolved by examining how we initialize our variables:
      variable       value

      var
       grade2 = document.getElementById("g2").value;

      We see that the value comes from the ID of the form element, and then it is put into the variable with the assignment operator (=). The easiest thing to do to convert the string value to a numerical value, would be simply to put it into the parseInt function like so:

      var grade2 = parseInt(document.getElementById("g2").value );

      Notice that the whole statment -- document.getElementById("g2").value -- is placed between the parentheses of the parseInt() function. That is because that whole thing is what represents the value in the form field.
    7. The next thing we must do is make certain that we prevent anyone from typing anything in the form fields other than numerical values, as non-numbers will get NaN as a return value, Not a Number. To do this we use a conditional (if...else) statment, but we must make sure of two things, that grade1 is a number AND that grade2 is also a number; however, we actually have to ask the question backwards, if it is NOT a number instead of if it IS a number. The distinction is important because we use a special built-in function for it, isNaN(), which asks whether a given value is NOT a number. If the value IS NOT a number, then the function returns true, and so, predictably, if the value IS a number, then the function returns false. This will work well with a conditional statement, which, if you remember, has the following form:
          if(condition)
          { // runs if condition is true
            statement;
            statement; etc.
          }
          else
          { // runs if condition is false
            statement;
            statement; etc.
          }
      Since the condition runs on boolean data, must be either true or false, and since the isNaN() results in boolean data, then we can put the isNaN() function inside the condition, as follows:
          if(isNaN(data value))

      Therefore, if the data value above is not a number then isNaN() will return true. If isNaN() returns true, then the condition will be true and the first part of the if...else statement will be run. If, on the other hand, the data value is a number, then isNaN() will return false, and the condition will be false. This means that the else part of the if..else statement will be run.
          In order for this to work for us properly, we should stop the script from running, or, more specifically, we should stop the document.write() part of the script from running unless the user types in ONLY numbers in the form fields. Since the isNaN() function returns true only if the data is NOT numerical, then the true part of our conditional (if...else) statement should be an alert() telling the user to type in only numbers:

          if(isNaN(document.getElementById("g1").value))
          {
            alert("You must type NUMBERS only")
          }
      and the false part of our conditional statement will contain the document.write()
          else
          {
            document.write("<img src = ‘images/sky.gif’ alt = ‘grade two’ height = ‘10px’ width = ‘" + grade2 + "px’/>" + grade2)
          }

    8. But we must remember that we have TWO conditions: 1) grade1 must be a number; 2) grade 2 must also be a number. Therefore we will have to use the OR operator within the condition as follows:
      if(isNaN(document.getElementById("g1").value) ||isNaN(document.getElementById("g1").value))

      The addition of this operator makes certain that if either one condition or the other is false, then the WHOLE condition of the if() statement is false, and the else statements get run instead. Nearing completion, then, the whole script looks like this:
          <script language="javascript" type="text/javascript">
            <!--
            function writeText()
            {
              var grade1 = parseInt(document.getElementById("g1").value);
              var grade2 = parseInt(document.getElementById("g2").value);
              var average = (grade1 + grade2)/2;

              if(isNaN(document.getElementById("g1").value) || isNaN(document.getElementById("g2").value))
              {
                alert("Please type only NUMBERS!");
              }
              else
              {
                document.write("<img src = ‘images/sky.gif’ alt = ‘grade one’ height = ‘10px’ width = ‘" + grade1 + "px’/>" + grade1);

                document.write("<img src = ‘images/sky.gif’ alt = ‘grade two’ height = ‘10px’ width = ‘" + grade2 + "px’/>" + grade2);

                document.write("<img src = ‘images/purple.gif’ alt = ‘average’ height = ‘10px’ width = ‘" + average + "px’/>" + average + " average");
              }

            //-->
          </script>

    9. Finally, we can concern ourselves with where the script writes the code containing the images. Up until now, we have used the document.writefunction, but there is another way: if you wish to write code and text into the current document instead of a new document, then you have to place it in between a pair of pre-existing HTML tags with its own ID.
          The best candidate for this is a pair of
      <div> </div> tags. These tags are ideal for a few reasons: 1) because they are block-level tags; 2) because they can be used to create layers; 3) because they do little to affect the page by themselves without anything (text or otherwise) between them, which means you can place a pair of <div> </div> tags in a page of HTML code without affecting it much. They can sit there invisibly within the code with their ID waiting to receive directions from a JavaScript to write text or code between them, like so: <div id="graphLayer"> </div>. As you already know, this ID can be called upon using the built-in function, getElementById(). Unlike our previous uses of this function with form elements, we are not asking for its value. Instead, we want to place some code between the tags. Therefore, instead of .value, we place .innerHTML afterwards like so: document.getElementById("graphLayer").innerHTML. Knowing this, all we have to do next is define what it is we want to go between those tags, and as mentioned before, we want to put the code from the three document.write() functions there:
        document.getElementById("graphLayer").innerHTML
      =
      "<img src = ‘images/sky.gif’ alt = ‘grade one’ height = ‘10px’ width = ‘" + grade1 + "px’/>" + grade1 +

      "<br/><img src = ‘images/sky.gif’ alt = ‘grade two’ height = ‘10px’ width = ‘" + grade2 + "px’/>" + grade2 +

      "<br/><img src = ‘images/purple.gif’ alt = ‘average’ height = ‘10px’ width = ‘" + average + "px’/>" + average + " average";


Thursday, June 14, 2007

Summer 2007

week 5: 6/15

hi everybody, i hope you've not forgotten that we have a blog for this class because it seems that i sure did. strange that no one saw fit to remind me of this fact before tonight.
hmmmm...THANKS MOSI!! <---there's your reward.

anyways, here's what we did in the last class down below. although this is only the day before our class, i'm sure that the homework won't be too much for you all.
carter-



  1. TOPICS:
    • LINK   Reviewing HTML Forms,
    • LINK   Reviewing some CSS,
    • LINK   Using the getElementById() function,
    • LINK   Event Handlers: 'Calling' or activating a user-defined function with something other than a link,

  2. HOMEWORK:
    1. Using the files that we began with last Friday, please make sure that your script functions up to the point that we brought it by the end of class. Use this week's posting here to help guide you through understanding what we began with, as well as how to begin clearing up any bugs in your script that you might have. Remember, Mozilla Firefox will assist you to a much higher degree than many other browsers, namely Internet Explorer. There may be minor differences here from waht we did in class, but they are essentially the same.
    2. Using more CSS, among other items, create another LAYER with the following criteria:
      • It should be exactly the same size as the first layer;
      • It should be exactly the same shape as the first layer;
      • It should be positioned directly to the right of the first layer;
      • The top and bottom edges of this new layer should be directly aligned with the first layer;
      • In this layer, there will be no visible content.
    3. Instead of an alert() function, make the results of the script output into a document.write() method.
    4. Create six tiny images with the following properties:
      • Each one is one pixel by one pixel in size.
      • Each one is set to 72ppi.
      • Each one has a different background color—red, orange, yellow, green, blue, purple.
      • Save all these little images in an images folder inside the main folder of last week's script.


     
  3. REVIEW: Last semester, in DMA110, you were introduced to XHTML and CSS. Below is a brief review of a few important elements of each:
    1. HTML Forms & Tables—The best-looking, most functional, and clearest FORMS are those that use TABLES for layout purposes. Examine the code below. Notice there are four (4) rows, and that rows 2 and 4 have form elements:

      <form id="myForm">
        <table border="0px" width="100&pct;">
      1  <tr>
            <td colspan="5">&nbsp;</td>
          </tr>
      2   <tr>
            <td>&nbsp;</td>
            <td>homework:</td>
            <td>&nbsp;</td>
            <td>
              <input type="text" id="hw"/>
            </td>
            <td>&nbsp;</td>
          </tr>
      3   <tr>
            <td colspan="5">&nbsp;</td>
          </tr>
      4   <tr>
            <td colspan="3">&nbsp;</td>
            <td>
              <input type="button" id="myButton" value="send" onclick="writeText()"/>
            </td>
          </tr>
        </table>
      </form>
      table1
      Notice that above the four (4) rows of the table and how they organize and lay-out the form. Now, compare to the table below without the borders.

      table2

      You should recognize that the table elements are aligned with each other. Such alignment adds a sense of organization, clarity, and coherence to any design, with only greater effects when using more form elements. In addition, you should also notice that each of the form elements, as well as the form itself, has an ID. These will be important when adding the CSS and JavaScript.
          Using the same basic layout set by the table, seven (7) more form elements may be added:

      table3

       
    2. CSS—The best method to further the design of a form such as this is to use CSS. Since we have begun the layout and design process with the assistance of tables to aid in alignment and organization, CSS can be used to advance our aims to create a pleasing design to a much higher degree of control.
      1. There are many ways to design using CSS. It is very individual and personal the way you proceed, but first I would like to simply set the background color for the page:
        <style type="text/css">
        <!--
          body   {background-color:#99aacc;}
        //-->
        </style>

      2. Next, I want to create a CSS CLASS which, when applied, will design the font and set the text-alignment for certain cells. I will call this class "formLabel":
        <style type="text/css">
          <!--
          body     {background-color:#99aacc;}

        .formLabel {font-family:Gill Sans,
                      Arial, sans serif;
                    font-size:14pt;
                    font-weight:bold;
                    color:#336699;
                    text-align:right;
                    line-height:10pt;}
          //-->
        </style>


        This class should be applied to only the <td> tags which have text, like so:

           <td class="formLabel">homework:</td>

        If applied to all the <td> tags with text (homework, classwork, mid-term exam, mid-term project, final exam, final project, and attendance), then the table will look similar to the image that follows.
        table4

      3. If we next create a layer using an CSS ID, then we can apply it to the table and form below, which will enable us to position it where we like, as well as control many aspects of its appearance.
            But first, let us establish the layer properties: it's width & height, it's position on the page with the top & width & position properties, and it's stacking order with the zIndex property.

        <style type="text/css">
          <!--
          body     {background-color:#99aacc;}

        .formLabel {font-family:Gill Sans,
                      Arial, sans serif;
                    font-size:14pt;
                    font-weight:bold;
                    color:#336699;
                    text-align:right;
                    line-height:10pt;}

        #layerOne {width:300px;
                    height:300px;
                    top:50px;
                    left:200px;
                    position:absolute;
                    zIndex:1;}
          //-->
        </style>

      4. After doing this, you must type a pair of <div> tags around the the <form> tags, and then apply the ID to the first one, like so:

          <div id="layerOne">
          </div>


      5. As a result, the form and table should move down and to the left some. If so, then we may then apply the styling we wish to the layer with border-style, border-width, border-color, and the background-color properties.

        #layerOne {width:325px;
                    height:400px;
                    top:50px;
                    left:200px;
                    position:absolute;
                    zIndex:1;
                    border-style:double;
                    border-width:3px;
                    border-color:#336699;
                    background-color:#aaccff;}
          //-->
        </style>

        All of this produces the following table when saved and refreshed:
        table5


     
  4. INTRODUCE:
    1. document.getElementById()—This is a JavaScript built-in function that searches throughout an HTML document for an HTML tag with a particular ID. Once located, this function selects the ID which will enable the script to manipulate it in some way. For example, if there is an ID by the name of "homework", the document.getElementById function may select it in this way:
        document.getElementById("homework").
      The script will activate the "homework" ID and thereby will be able to manipulate it. If it is an H1 tag or a H2 tag or a P tag, it may change the color of the text, or the size or various other properties. If it is a form element, it may be able to extract the data from it. It does so in this way:  document.getElementById("homework").value, where value is whatever is typed in the blank of that particular form element.
          In the form we have typed, we have seven (7) form elements. We are able to extract whatever data the user types in those seven blanks with this new function. Below I create seven new variables, and then use the document.getElementById() function to move the data from the form elements into the variables. Finally, all is revealed with a series of alert() functions.

      <script language="javascript" type="text/javascript">
      <!--
      function writeText()
      {
        var red = document.getElementById("hw").value;
        var orange = document.getElementById("cw").value;
        var yellow = document.getElementById("mtE").value;
        var green = document.getElementById("mtP").value;
        var aqua = document.getElementById("fE").value;
        var blue = document.getElementById("fP").value;
        var purple = document.getElementById("att").value;

        alert(red);
        alert(orange);
        alert(yellow);
        alert(green);
        alert(aqua);
        alert(blue);
        alert(purple);
      }

      //-->
      </script>

       
    2. Event Handlers—In JavaScript there are a series of terms that cause things to happen, much like built-in functions; however, unlike them, they make things occur as a result of certain 'computer events'. These events are peculiar to computers, events such as loading a browser window or web-page, or closing a web-page or browser window, such as clicking with the mouse or moving the cursor with the mouse. These are all events which occur in a computer environment. Event handlers use these events to cause other things to occur, such as making something appear or disappear when you click on a button with a mouse. The click of the mouse is the event that the event handlers handle. The appearance of a pop-down menu when you click on the mouse is the action that the event handlers cause to occur. Some common event handers are: onLoad, onUnload, onmouseOver, onmouseOut, onClick, etc.
          Like the <a> anchor tag, event handlers can be used to call or activate user-defined functions. We can use an event handler to activate our function above with the submit button in our form. We do this in the <input/> tag itself:
      <tr>
        <td colspan="3"> &nbsp;</td>
        <td>
         <input type="button" id="myButton" value="send" onclick="writeText()"/>
        </td>
        <td>&nbsp;</td>
      </tr>


Monday, June 04, 2007

Summer 2007

week 4: 6/01

hi everybody,
hope you had a nice weekend, but now here we are with another week ahead of us. you all did great in the last class. i felt very good about how the class is going so far when i left TCI for the weekend. so please, as i mentioned in class on friday, don't fall behind with your homework.

please let me know if you need help.
carter-


  1. TOPICS:
    • LINK   Defining: Operations, Operators, Operands,
    • LINK   More on Conditional Operations,
    • LINK   More on User-Defined Functions,
    • LINK   Introducing IF/ELSE Statements (Conditional Statements),
    • LINK   A review of the primary issues discussed in the first three (3) classes,

  2. HOMEWORK: Using Notepad or TextPad (or TextEdit with a Mac), please type an .html document with all the necessary scripts listed below. Where possible for the questions, create user-defined functions:
    • Do the questions from the end of chapter 6;
    • Please do the following script
      1. First, requests the user's name;
      2. Second, requests a number from the user;
      3. Third, requests a 2nd number from the user;
      4. Fourth, determines whether the 1st number is greater than, less than, or equal to the 2nd number using conditional statements (IF/ELSE);
      5. And then, that finally tells the user (using his/her name) whether the first number or second number is greater via an alert() function.
           Click Here to see example below:





     
  3. REVIEW: During these first three (3) weeks of class, you have been introduced to the three types of data defined by JavaScript:
    1. JavaScript Data Types
      1. Numerical Data—Perhaps the easiest type to recognize as it pertains to something intuitive, that we deal with on a daily basis, number. It includes all numbers, both positive (greater than zero) and negative (less than zero), integers (whole numbers such as 1, 2, 3, -17, 200, etc.), and decimals (1.5, .23, 22.87, etc). Moreover, it also includes numerical expressions; that is, numbers expressed in terms of equations, simple equations such as 1 + 1, more complex equations such as 5 * ((5 + 1) / (25 - 8)), as well as much more complicated mathematical equations that include geometrical, algebraic, and trigonometric functions, and calculus.
      2. String Data—This is also relatively intuitive as the term itself, STRING, refers simply to a 'string of characters' set between quotation marks. Characters here refers to any alpha-numeric character (numbers and letters), both lower and upper case, the hypen, the underscore, as well as all the other characters used in HTML. String data can be common English, such a a word ("hello"), a phrase ("very good food"), or longer strings such as sentences or paragraphs, or even whole 'pages' of HTML.
      3. Boolean Data—This includes simply the values TRUE and FALSE, and their numerical equivalents, 1 and 0.

    2. JavaScript Basic Built-in Functions
        You have also been introduced to some basic built-in JavaScript functions. Remember, a function is a an action that JavaScript takes. The built-in functions we have covered up to now are as follows:
      1. alert()—Perhaps the easiest function to remember, it causes the browser to display a small 'alert' window. It is designed as a ONE-WAY communication of information (data) from the browser or script to the user. It is NOT interactive in that the user cannot respond by sending any information of his/her own.
      2. document.write()—Like the alert(), the document.write() is designed as a ONE-WAY communication of information (data) from the browser or script to the user. It is NOT interactive in that the user cannot respond by sending any information of his/her own; however, it does not produce an alert box. Instead, the information is 'written' directly into the browser window, the page itself, otherwise known as the 'document'. For this reason, the information sent from the script or browser, may also contain HTML or CSS.
      3. prompt()—This function is similar to the alert box in that it produces a small window that pops up above the browser window. Also similar is the fact that some information or data is sent by the script to the user, usually in the form of a request for information. As a result, this function IS in fact interactive in that the user does provide some data of his/her own back to the script, thus affecting the outcome. The type of data the user sends back is restricted only by the request made.
      4. confirm()—This function is also similar to the alert function in that it produces a small window that pops up above the browser window. Furthermore, it is similar to the prompt() function as well in that this function is also interactive. The user here must also provide some data of his/her own back to the script, and likewise affecting the outcome. However, the type of data the user sends back may only be in the form of boolean data as the space provided for responding to the request in the confirm box comes only in the form of 2 buttons, OKAY (true) and CANCEL (false). The request, then, must fit the restraints of this model in that TRUE or FALSE must be satisfactory responses.
        EXAMPLES:

            Good—Click okay if you need more time.
            Bad—What color is your hair?
      5. parseInt()—This function is different than the other four listed above in that it does not necessarily produce any physical changes or results, such as the appearance of a pop-up window, or the change of the appearance of the web-page itself. What it does is perhaps more typical of most JavaScript functions as it works INTERNALLY on the script itself, more specifically, altering the data within the script somehow. The task of this function is to change one type of data into another type of data, from STRING DATA to NUMERICAL DATA. The term 'parseInt' broken down refers to the phrase "Parse the data provided as an Integer", which simply means PROCESS AS A WHOLE NUMBER. The string data is placed between the parentheses, and the function, parseInt(), will therefore convert it from a string to a number, such as:
            parseInt("1001") = 1001 >> converting the string "1001" to the integer 1001.

    3. Variables—A variable in JavaScript is a special item. It serves as a container, like a cup, but which instead of containing liquids and drinks stores a single piece of information, or data. Once created, a variable may contain any piece of data of any type (numerical, string, boolean), but it may only contain one element of data at a time. This piece of data that it stores is known as its value. Moreover, this value may be changed at any time and as many times as required.
          A variable is created, or declared with two things:
      1. var keyword
      2. unique name

      A variable is then given some data to hold, assigned a value, by using the assignment operator   = and then its value. To give a variable some data, to assign it a value, for the first time is called initializing a variable.
      1. declaring a variable —> var myName
      2. initializing a variable —> myName = "Carter"


     
  4. INTRODUCE:
    1. Operations: An operation consists of two (2) parts, Operators and Operands, demonstrated here with two (2) different kinds of operations:
                    o p e r a t i o n
          5         +         5
        operand 1     operator     operand 2
          6         <         9
                    o p e r a t i o n
      1. Arithmetic Operations—these are numerical expressions by which data is manipulated by a particular operator. Data manipulation here refers to simple exercises such as addition and subtraction. For example, each of the following is a numerical operation:
            10 + 10,
            10 - 10,
            10 * 10,
            10 / 10, and
            10 % 10

        They are numerical operations because they result in a single numerical value.

      2. Comparison Operations—these are not numerical operations in that they do not manipulate numerical data (they do not move or change numbers). The operators here (the symbol in the middle) are not used to produce a sum or a product at the end, resulting in a single piece of numerical data. The result from these is a simple true or false. The script evaluates a comparison between two pieces of data, such as two numbers, and tries to determine if it is true or false: For example, each of the following evaluates a comparison between two numerical values:
            10 < 10,
            10 > 10,
            10 <= 10,
            10 >= 10,
            10 !< 10,
            10 !> 10,
            10 == 10, and
            10 != 10


      3. Concatenation—Technically, this is just one of many different JAVASCRIPT OPERATIONS; however, because of its importance and widespread, ubiquitous usage, I have discussed it since the first class. Furthermore, I believe it deserves review and mention here. Its actual definitions are as follows:
        1. To connect or link in a series or chain.
        2. Computer Science. To arrange (strings of characters) into a chained list.
        Both above are significant to us: it is simply placing one character after another in a chain, or even one chain of characters after another chain of characters. What we are speaking about here then is STRING data. In order for concatenation to occur, there must be string data present, but it may also involve other types of data, as the example below suggests. The two (2) short strings here combined:
            "Hello, " + "how are you?"
        result in the longer string
            —>
        "Hello, how are you"
        Here are some other examples of concatenation:
            "Carter" + "Johnson",
                    —> "CarterJohnson"

            "March" + 11,
        —> "March11"

            "March" + "11",
        —> "March11"

            "March + 11",
        —>
        "March + 11"

            "March + 11 =" + "March" + "11",
                    —>
        "March + 11 = March11"


         
      4. Conditional Operations—like comparison operations, these are not numerical operations either in that they do not manipulate numerical data (they do not move or change numbers). However, they are quite different otherswise: they are the ONLY operations that take three (3) operands; but only the first operand is evaluated, and this is based on whether it is TRUE or FALSE. If the first operand evaluates to true, then the second operand is passed as the returned value, and the third is dismissed altogether. However, if the first operand evaluates to false, then the second operand is dismissed, and the third operand is the one that is passed as the returned value. It follows the following form:
                c o n d i t i o n a l   o p e r a t i o n
            (6 < 9) : "Ha Ha!" ; "Hee Hee!";
            operand 1       operand 2       operand 3


       
    2. User-Defined Functions: There are many built-in functions that make up many of the actions that JavaScript can take. However, a scripter may define her own functions, thereby giving JavaScript new actions to take. Such user-defined functions are actually containers, much like variables; however, unlike variables which hold a single piece of data, a function is a container which hold actions, or rather the code that causes certain actions to occur. A user-defined statement, then, contains JavaScript statements.
          To declare a user-defined function you must type four (4) things:

      1. the function keyword,
      2. a unique name,
      3. a pair of opening and closing parentheses, and
      4. a pair of opening and closing curly brackets.

      Since it has been established that all functions, including user-defined functions, are really containers for code that, when activated, cause JavaScript to take certain actions, it must be made clear where this code goes: it is placed in between the curly brackets. The opening bracket and closing bracket indicate the extents of the code included in the function. Once code is placed between the brackets, it will not be activated unless called upon.

          A function is called by using its name followed by the pair of parentheses. One common way this is done is with a link, where, instead of the URL placed after the HREF attribute, the name of the function is placed there as follows:

              <a href="javascript:myFunctionName()"> click here </a>
      where the name of the function, the function being called, or activated, is myFunctionName().

      Examples—the following are some examples worked out in class of scripts using conditional operations:

      1. positive/negative number: LINK
        <script language="javascript" type="text/javascript">

         function posNegFun()
          {
           var userNum = parseInt(prompt("Please type a number in the blank below.","");

           var temp = (userNum < 0)? "NEGATIVE" : "POSITIVE" ;

           alert("Your number, " +userNum+ ", is " +temp);
          }

        </script >


      2. okay/cancel button: LINK
        <script language="javascript" type="text/javascript">

         function confirmFun()
          {
           var confirmVar = confirm("Please click one of the buttons below, OKAY or CANCEL.");

           var temp = (confirmVar)? "OKAY" : "CANCEL" ;

           alert("You clicked the " +temp+ " button");
          }

        </script >


      3. odd/even number: LINK
        <script language="javascript" type="text/javascript">

         function oddEvenFun()
          {
           var userNum = parseInt(prompt("Please type a number in the blank below.","");

           var temp = (userNum % 2)? "ODD" : "EVEN" ;

           alert("Your number, " +userNum+ ", is " +temp);
          }

        </script >


       
    3. Conditional (IF/ELSE) Statements: If...else statements are known as CONDITIONAL statements because they rely on a condition before selected code is executed. For example, on the condition that the user clicks okay in a confirm() function, some code may be executed. The first part of the statement always begins with the IF keyword followed by the condition set between parentheses:
          if (100 >10)
      If the condition, set between the parentheses above, evaluates to TRUE, then some selected code is executed. Since 100 is in fact greater than 10, then the condition would evaluate to true. As such, whatever code below the condition set between curly brackets will be executed. Otherwise, if the condition does not evaluate to true, if it evaluates to FALSE instead, then the code between the curly brackets is NOT executed:
        if (100 >10)
        {
          alert("The condition is TRUE!");
        };

      If the condition between the parentheses evaluates to true (which in this case it would), then the code between the curly brackets (the alert() function) would be executed. But if the condition does not evaluate to true, then the alert would not be executed. In that case, a second part could be added to take into consideration the possibility that the condition could return FALSE. If so, then another set of code could be executed if there is an else following it as such:
        if (100 >10)
        {
          alert("The condition is TRUE!");
        }
        else
        {
          alert("The condition is FALSE!");
        };

      If there is more than one condition to test for, then you must add an additional IF statement for each condition that the code must test for:
        if (userNumber >10)
        {
          alert("The number is GREATER than 10!");
        }
        else if (userNumber <10)
        {
          alert("The number is LESS than 10!");
        }
        else
        {
          alert("The number is EQUAL to 10!");
        };


      if/else...if statements: LINK

      There need only be 2 test conditions (and therefore only 2 IF statements) because if the user's number is not greater than 10, and if it is not less then 10, then the only other possibility is that it is equal to 10. There doesn't need to be a condition to test for this possibility.