Saturday, February 24, 2007

Spring 2007

week 6: 2/23

Hello my friends,
I'm happy with the way class went last night. I know that 3 hours to spend on JavaScript is a long time to spend anytime, particularly on Friday night, but you all did well with the material we covered last night. However, we won't always have enough in class to do the homework that should've been done the week before as we did last night in the beginning of class. For those of you who haven't been checking the blog or doing your homework (and there are quite a few of you), your grades are already suffering. So, please try not to forget to do your homework. It is a big part of the grade for this class, and it will help you to understand what we do the next week in class.
    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 last week 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, March 2) 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. 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:

    • LINK   Mid-Term Project—also due in three weeks, check blog during week for additional reading material to download for this project. I have yet to cover most of requirements for this project; however, I will address each issue in the next two classes.
    • 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";


Monday, February 19, 2007

Spring 2007

week 5: 2/16

hi everybody, i hope you've had a nice long weekend, even though it has been icy outside. hopefully, this week it will be a little warmer.

anyway, below you will find this week's posting for our class on friday. you will probably notice that although the results are very very similar, that the CSS is somewhat different. as you go along with coding, you will find that there are often many ways to achieve similar results. i give you another example of how to achieve similar results on your page with CSS. if you are not certain how it works, please study the example. figuring out how things work with CSS require a bit of simple trial and error. just take things out and see how it changes the way the document appears.

regarding the javascript, it is basically the same as what we did in class. please, bring what we did last week to class again this week. we will finish up the script and add some color.


  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.
    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. In addition to outputting the values of the variables (red, orange, yellow, green, blue, purple), the document.write() function should also output the tiny images that we created with PhotoShop. The red image should be next to the red variable, the orange image should be next to the orange variable, yellow image should be next to the yellow variable, and so on.

     
  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>


Friday, February 09, 2007

Spring 2007

week 4: 2/09


  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 TextEdit with a Mac), please type an .html document with a script that creates a user-defined function that does the following:
    • First, requests the user's name;
    • Second, requests a number from the user;
    • Third, requests a 2nd number from the user;
    • Fourth, determines whether the 1st number is greater than, less than, or equal to the 2nd number using conditional statements (IF/ELSE);
    • And then, that finally tells the user (using his/her name) which one it is 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.

Sunday, February 04, 2007

Spring 2007

week 3: 2/02

Hello everybody,
Welcome to the blog for DMA106, JavaScript, to those of you who haven't visited yet. By now, hopefully, everyone who is going to be in this class this term has made it to class at least once. If you haven't, then you need to make sure you speak to me this week sometime (2/5 - 2/9). We have already met for three classes, and if you haven't been yet then you are seriously behind. Although this blog is meant to serve as a supplement to the class, and it definitely can go a long way to keeping you caught up if you miss a class here or there, as I will repeat here almost everything I cover in class, it is by no means a replacement. Please remember, your grade will suffer seriously if you do not attend class.
    I think we did a lot of nice work this past Friday, and I was quite happy with how you all seem to be picking up the material. Not that it is easy by any means for most of you, but I can see you getting it little by little. You'll notice by now that a little bit of persistence, and a lot of tedious attention to detail really pay off. Also, if you cannot get something in the homework on your own, please find someone (especially me) to help you during the week before your homework is due.

Good Luck, Carter-

  1. TOPICS:
    • Operators:
      • LINK   Numerical Operators,
      • LINK   Comparison Operators,
      • LINK   Logical Operators,
      • LINK   Assignment Operators
    • Operations:
      • LINK   Numerical Operations,
      • LINK   Comparison Operations,
      • LINK   Conditional Operations
    • LINK   User-defined Functions:
    • New Built-in Functions:


  2. HOMEWORK:
    1. From the book—Using Notepad, Textpad, or TextEdit (Mac), please type an .html document that contains the following questions and answers from the book (please include all necessary scripts):
      1. Chapter 4: 1, 2 and 3;
      2. Chapter 5: 1, 3 - 5, and 7;


  3. INTRODUCE:
    1. Operators: In the last class, you were introduced to the elements in JavaScript known as operators. Below, you will find listed many of the ones we will consider in class this term:
      1. Numerical Operators:
        1. Addition ( + ) —Combines two quantities (numbers) to form a sum.
        2. Subtraction ( - )—Reduces one quantity by another quantity.
        3. Multiplication ( * ) —The process by which one quantity is added to itself a given number of times: also ×.
        4. Division ( / ) —The process of determining precisely how many times one quantity is contained in, or may be divided by, another quantity: also ÷.
        5. Incrementation ( ++ ) —The process of increasing a quantity by one.
        6. Decrementation ( -- )—The process of decareasing a quantity by one.

      2. Comparison Operators:
        1. Less Than ( < ) —Compares two quantities (numbers) based on whether one is smaller than the other or not.
        2. Greater Than ( > )—Compares two quantities (numbers) based on whether one is larger than the other or not.
        3. Less Than or Equal To ( <= ) —Compares two quantities (numbers) based on whether one is smaller than the other or whether they are the same.
        4. Greater Than or Equal to ( >= ) —Compares two quantities (numbers) based on whether one is larger than the other or whether they are the same.
        5. Not Less Than ( !< ) —Compares two quantities (numbers) based on whether one is NOT smaller than the other.
        6. Not Greater Than ( !> ) —Compares two quantities (numbers) based on whether one is NOT larger than the other.
        7. Equal To ( == ) —Compares two quantities (numbers) based on whether they are the same or not.
        8. Not Equal To ( != ) —Compares two quantities (numbers) based on whether they are NOT the same.

      3. Logical Operators:
        1. And ( && ) —An element used to combine two operations or solutions as one compound operation or one compound solution.
        2. Or ( || ) —An element used to present an option between two or more solutions or operations.
        3. Not ( ! ) —An element which eliminates the possibility of a particular solution or operation.

      4. Assignment Operators:
        1. Assignment ( = ) —An element used to provide a new value to another element such as a variable or array.
        2. Assignment-Addition ( += ) —An operator used to increase the current value of an element by a given number and assign the element the new value.
        3. Assignment-Subtraction ( -= ) —An operator used to decrease the current value of an element by a given number and assign the element the new value.


    2. Operations—these are actions taken upon elements of data, on numbers and strings for example, by operators that change or alter their values in some way.
      1. Numerical Operations—This group of operations are perhaps the most intuitively to our understanding than most of the others. Save one or two of them, they need no real explanation; therefore, below you will see examples of various numerical operations:
                  o p e r a t i o n
            5             −             1
          operand 1     operator     operand 2
            3             ×             8
          operand 1     operator     operand 2
            4             ÷             2
          operand 1     operator     operand 2
            7             %             2
          operand 1     operator     operand 2
            6             +             9
                  o p e r a t i o n

         
      2. Comparison Operations—This group of operations are probably also recognizable at first glance; however, the results of these operations are probably less than clear, no pun intended. If we are to understand operations in the way they are defined above, as actions upon elements of data resulting in another element of data, then maybe it can be made more clear. In this case, the resulting data is of a completely different type. If what is being compared by the operators are two numerical values (two elements of numerical data), then the result is actually an element of boolean data. What results from all of the operations below, is simply a true or false:
                  o p e r a t i o n
            5             <             1
          operand 1     operator     operand 2
            3             >             8
          operand 1     operator     operand 2
            4             ÷             2
          operand 1     operator     operand 2
            7             <=             2
          operand 1     operator     operand 2
            6             >=             9
          operand 1     operator     operand 2
            3             !<             3
          operand 1     operator     operand 2
            8             !>             9
          operand 1     operator     operand 2
            6             ==             6
          operand 1     operator     operand 2
            4             !=             4
                  o p e r a t i o n

         
      3. Conditional Operations—These operations are arguably the most NON-intuitive element within the whole of the JavaScript scripting language. The reason I say this is that there is nothing in our prior education that might suggest to us how to interpret them. Without having the structure explained to us first, an example of one of these operations would probably remain inscrutable. That being said, once described and demonstrated, they are rather simple to use. Much like learning new words, it just takes a bit of time for us to learn their meanings and then to get used to employing them ourselves.
            First, unlike all other operations we have considered such as the examples above, this is the only type with three (3) operands. Moreover, they do not employ any of the operands discussed so far in class. Their structure follows the following pattern:

              conditional operation structure
            operand 1 ?   operand 2 :   operand 3 ;

                    conditional operation
        example: (5 < 6) ? "doremifa" : "solatido" ;

        Now, let us see if we can understand what's going on with this operation: in this kind of operation, the computer only evaluates the first operand. But what does this mean? What does it mean to evaluate? In this case, the computer will only consider, process, or calculate the first operand. The computer will not evaluate in any depth the second or third operands. Their meaning or values is of no consequence to the function of this operation. However, the value of the first operand, is of great consequence. The computer will evaluate the first operand and attempt to determine whether it equals, or is equivalent to, or evaluates to true or false.
            To simplify matters, in my example above, I have only made the first operand meaningful. The second and third operands are just seemingly random strings of characters. The computer wouldn't be able to make real sense of these two anymore than we could. The first one, on the other hand, will either be true or false.
            In this case, five is indeed less than six, so this little expression—the first operand—will evaluate to true, and not false. But what does this mean? What happens after that?
            In this sort of operation, if the first operand evaluates to TRUE then the result of the operation is operand 2; however, if the first operand evaluates to FALSE then the result of the operation is operand 3. Therefore, in the above example, since 5 is less than 6, it is the same as true: the first operand then is true. The result of this conditional operation is therefore operand 2, which is equal to the string, "doremifa".
       
    3. User-defined Functions—In JavaScript, a function is an action that is performed or taken by JavaScript. Another name for a function is the term method as there is no difference between the two elements. For reasons that will be explained at a later time, the terms are often used interchangeably. Up to this point already in the first three weeks of class, we have identified a number of built-in functions that help to form the basis of what JavaScript does as a scripting language. Each of these functions performs an action: alert() , confirm() , prompt() , parseInt() , and typeof() . Now, whether we use these functions that have already been defined by the language itself, or whether we as users and programmers create and define our own functions makes little difference. A function is always visually identified by the pair of opening and closing parentheses that follows its name, and it always performs an action or series of actions. A user-defined function is no different. Here are the four (4) elements required for creating a new user-defined function:
      1. the function keyword
      2. a unique name that is not one of the reserved JavaScript keywords;
      3. a pair of parentheses to enclose what we will later learn are called parameters, or arguments;
      4. a pair of curly brackets that delimits the extents of the code to be included in the function.
       

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

      1.   function compOp()
      2.   {
      3.    var userNum = prompt("Please type
      4.        a number.","");
      5.    var temp = parseInt(userNum);
      6.    var ans = (temp % 2)? "ODD" : "EVEN";
      7.    alert("Your number, " + temp +
      8.        ", is "+ans);
      9.   }

       //-- >
      </script>

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

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

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

        Line 5:
        var temp = parseInt(userNum);
        The second variable declaration and its initialization including:
        1. the var keyword;
        2. the unique name of the variable: temp;
        3. the assignment operator; and
        4. the value assigned, which is a JavaScript built-in function, parseInt(), which converts string data to numerical data. Recall, that anything that the user types into the prompt() function will, strictly speaking, be a string. Therefore, in order for any numerical operations are to be performed on this user's number, it must first be converted from a line of characters (string data) to numerals (numerical data) Without this, the remainder of the script will not function properly.

        Line 6:
        var ans = (temp % 2)? "ODD" : "EVEN";
        The third variable declaration and its initialization including:
        1. the var keyword;
        2. the unique name of the variable: ans;
        3. the assignment operator; and
        4. the value assigned, which comes from a conditional operation. The first operand uses the modulo operator which provides the remainder when the number in temp is divided by 2. If the number is odd then the remainder will be 1. If the number is even, however, then the remainder will be 0. This is a lucky coincidence, because it just so happens that 0 & 1 are the numerical equivalents of FALSE and TRUE. Morover, they are what the conditional operation works with. If the remainder of operand1 is 1, then operand2, "ODD", will be the result of this operation; however, if the remainder of operand1 is 0 then operand3, "EVEN", will be the result. Try it and see if it works for you. Then, try switching the places of "ODD" and "EVEN" to see what happens.
              Whatever the result of the operation, it gets assigned to the variable, ans.

        Line 7-8:
        alert("Your number, " + temp + ", is "+ans);
        This line is a simple alert() function which concatenates a statement together so that the user can see whether his number is ODD or EVEN.
        1. The first term of the concatenated statement is the string—"Your number, ".
        2. The second term of the concatenated statement is the variable, temp, which contains the user's number entered in at the prompt at the beginning of the script.
        3. The third term of the concatenation is a very short string, ", is ".
        4. And the fourth and final term of the concatenation another variable, ans, which contains the result of the comparison operation, either the string "ODD" or the string "EVEN".

       
    4. New Built-in Functions—Below, find a couple of new Built-in Functions explained. Although we have not yet used either of these in class, they have come up in the reading, and I will be mentioning them from time to time. Please review and make sure you understand. A couple of quick experiments should do the trick to help you comprehend their place in a script.
      1. typeof()—This function works with a piece of data and identifies what its data type is, whether it is numerical, string, or boolean, for example:
            var myData = 1000;
            var myType = typeof(myData);
            alert(myType);

        Above, we have two variables. The first one has
        1000 as its numerical value. The second one is given a value by the typeof() function. Between the parentheses, you should notice that we have the other variable myData. This variable contains an element of numerical data, so the value of the variable, myType, will be numerical. Therefore, what you will see in the alert() box, is simply the word numerical.
      2. eval()—This function is similar to the parseInt() function in that it converts data from one form to another. In this case, it converts string data not into numerical data, but rather into JavaScript code itself. For example. it could convert the string "alert('hello, how are you?')" or even something as simple as "10 + 10" into a line of JavaScript code. Try a simple comparison between two alerts. They are typed like so:
            var myString = "10 + 10";
            var convertedString = eval(myString);

            alert(myString);
            alert(convertedString);